First, how switch works (really):
A switch usually considered a construct that selects a piece of code to execute depending on the value of some expression, as in
switch (x) { case 1: foo(); break; case 2: bar(); break; }
However, it is more accurate to think of switch as a form of the computed goto . For example, it is completely legal:
switch (x) { puts("I can't be reached"); case 1: if (cond) { case 2: puts("Either x == 1 && cond, or x == 2"); } }
Depending on the value of x program will go to case 1 or case 2 (or by switch if x is neither 1 nor 2).
Your program will compile as C (with junk values ββfor x and y inside the switch , as initialization is skipped), but not as C ++. The reason is that C ++ does not allow going to the case label in order to cross initialize the variable. For simple types such as int , int x; skipped int x; allowed (since initialization is not involved), but not passed through int x = 1; .
The main motivation for this difference is probably that switching to the case label of the initialization crossroads in C ++ would be unsafe if constructors are involved. For example, if C ++ allows the case label to occur after My_class my_object defined within a certain scope, then passing to this case label skips the my_object constructor, but still my_object its destructor when leaving the scope.
The same restrictions apply to goto in C ++. You cannot use it to go into a block even after the variable is initialized.
As a side note, switch follows the same general syntax as if and while . if syntax given in C11 (ISO / IEC 9899: 2011, clause 6.8.4),
if (expression)
whereas switch syntax is
switch (expression)
The only difference with respect to the statement (in C - C ++, a few more restrictions are added, as mentioned above) is that for switch allowed to contain case labels (and break ), but not for if (unless if not found inside the switch ) .
As with if , you can even leave curly braces and write code, as shown below. (Regardless of whether this is unnecessarily confusing, this is another discussion.)
switch (x) case 1: case 2: puts("x is 1 or 2");
Syntactically, case and default labels belong to the same category as goto labels. Section 6.8.1 of the C11 standard has the following definition:
labeled operator:
identifier :
case expression constant expression :
by default :