c++: switch statement missing semicolon before close brace

c++, compiler-errors, switch-statement, visual-studio

Solution

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.

Problem

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

Original source