c ++:switch语句在右括号前缺少分号

为了将来的读者和我自己以后的理智,我想绝对清楚地说明,没有 default 情况的 switch 语句(由于所有所涵盖的情况)或顺序 if-elseif-else 不能省略不应该做任何事情的最终 else 并且包含对此效果的注释(参见示例).

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

示例:生成编译器错误

开关(方向){案例 MOVE_UP://...休息;案例 MOVE_RIGHT://...休息;案例 MOVE_DOWN://...休息;案例 MOVE_LEFT://...休息;默认:/* 没做什么 */}

示例:不生成编译器错误

开关(方向){案例 MOVE_UP://...休息;案例 MOVE_RIGHT://...休息;案例 MOVE_DOWN://...休息;案例 MOVE_LEFT://...休息;默认:/* 没做什么 */;}

解决方案

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

<上一页>标签声明:标识符:语句case constant-expression : 语句默认:声明

C++11 是一样的,只是你可以在标签之前有属性.

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

也就是说,我不知道为什么 labeled-statement 的语法不允许 default: statementopt.如果是这样,那么如果你写了 default : case 1: break;,那么 case 1: break; 是否是 statement 属于 default:,或者 default: 是否没有自己的 statement,但紧随其后的是一个.它的含义仍然毫无疑问意味着,但也许人们认为它会弄乱人们的解析器.

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).

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?!

EXAMPLE: GENERATES COMPILER ERROR

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

EXAMPLE: DOES NOT GENERATE COMPILER ERROR

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

解决方案

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 is the same except you can have attributes before the label.

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

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.

相关文章