C ++:在右括号之前,switch语句缺少分号 [英] c++: switch statement missing semicolon before close brace

查看:89
本文介绍了C ++:在右括号之前,switch语句缺少分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了将来的读者和我以后的理智,我想明确指出没有 default 情况的 switch 语句(由于所有)或连续的 if-elseif-else 以及不应执行任何其他操作的最终结果,则不得省略,并应包括对此的评论(请参见示例).

In the interest of future readers and my own sanity later, I like to make it absolutely clear that switch statements that do not have a default case (due to all cases being covered) or sequential if-elseif-else with a final else that should not do anything must not be omitted and a comment to that effect be included (see example).

但是,每当我在 switch 语句中包含 default 案例并将其保留为空时,我都必须在 default 案例中放入分号,或者编译器错误:线[switch语句的右大括号行]缺少';'在'}'发生之前. 为什么?!

However, whenever I include the default case in the switch statement and leave it empty I must put a semicolon inside the default case or a compiler error: " Line [Line of closing brace of switch statement]`missing ';' before '}'" occurs. WHY?!

示例:生成编译器错误

switch(direction) {
    case MOVE_UP:
    //...
    break;
    case MOVE_RIGHT:
    //...
    break;
    case MOVE_DOWN:
    //...
    break;
    case MOVE_LEFT:
    //...
    break;
    default:
        /* DO NOTHING */
}

示例:不会产生编译器错误

switch(direction) {
    case MOVE_UP:
    //...
    break;
    case MOVE_RIGHT:
    //...
    break;
    case MOVE_DOWN:
    //...
    break;
    case MOVE_LEFT:
    //...
    break;
    default:
        /* DO NOTHING */;
}

推荐答案

6.1/1在C ++ 03中给出了标记语句的语法:

6.1/1 in C++03 gives the grammar for a labeled-statement:


labeled-statement:
    identifier : statement
    case constant-expression : statement
    default : statement

C ++ 11相同,除了可以在标签前添加属性.

C++11 is the same except you can have attributes before the label.

零长度的令牌序列不是C ++中的语句,因此, default:本身不是 labeled-statement

A zero-length sequence of tokens is not a statement in C++, hence default: on its own is not a labeled-statement.

也就是说,我不知道动机是什么,为什么 labeled-statement 的语法不允许 default: statement opt .如果确实如此,那么如果您编写 default:case 1:break; ,是否 case 1:break; 陈述属于 default:,或者 default:是否没有自己的声明,但后面紧跟一个.毫无疑问,它的含义是什么,但也许有人认为这会弄乱人们的解析器.

That said, I don't know what the motivation was why the grammar for a labeled-statement doesn't allow default: statementopt. If it did then there would be a grammatical ambiguity if you wrote default : case 1: break;, whether case 1: break; is the statement belonging to default:, or whether default: has no statement of its own, but is immediately followed by one. There's still no doubt what it means, but maybe it was thought that it would mess up people's parsers.

这篇关于C ++:在右括号之前,switch语句缺少分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆