comma in switch case [closed]

This usage of comma in case label is illegal in standard C++. It is simply grammatically incorrect. A conforming compiler must issue a diagnostic message in response to this code, even if it accepts it somehow.

There might (or might not) be some intricate details involved.

  • In the original C++98 language comma operator was prohibited form being used in case label. It was “blocked” by two different parts of language specification:

    Firstly, the grammar of constant-expression does not allow top-level comma operators in constant expressions. Grammatically, a comma operator can only appear in constant expressions enclosed in ().

    Secondly, C++98 specification explicitly prohibited comma operator in constant expressions at any level of nested () (see 5.19/1).

    (This was basically identical to C language requirements.)

  • However, C++11 made some changes: it allowed comma operator in constant expressions. Yet, the grammar was left unchanged. This means that comma operator is now allowed in constant expressions, but only when enclosed in (). E.g. starting from C++11 you can use

    case (1, 3, 5, 7, 9):

    which is an ordinary application of comma operator. It makes the whole thing equivalent to

    case 9:

Meanwhile, your

    case 1, 3, 5, 7, 9:

remains illegal in C++ to this day. If your compiler supports it somehow, it must be a language extension implemented by your compiler. Consult your compiler documentation to figure out what it means.

Judging by the output you got, your compiler sees case 1, 3, 5, 7, 9: as equivalent to case (1, 3, 5, 7, 9): and thus equivalent to case 9:. That explains the output. The program simply counts 9s and 10s in the input. You’ve got two 9s and three 10s.

See also:
Is the comma operator allowed in a constant-expression in C++11?
Why was the restriction on the comma operator being in a constant expression removed in C++11?

Browse More Popular Posts

Leave a Comment