c++: switch statement missing semicolon before close brace

拈花ヽ惹草 提交于 2021-02-16 19:36:11

问题


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 */;
}

回答1:


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.




回答2:


Because you need a statement for your default case. A semicolon is an empty-statement.



来源:https://stackoverflow.com/questions/10690328/c-switch-statement-missing-semicolon-before-close-brace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!