I'm curious about inserting the break inside a brackets in a case.
int a = 1;
switch (a)
{
case 1:
{
a = a;
break;
}
a = a;
case 2:
{
a = a;
}
break;
}
In the C++ code above, in case 1 I've inserted the break inside the brackets, it is an error?
Is there any difference between case 1 and case 2 in the example above?
Is there any difference between case 1 and case 2 in the example above?
In terms of the execution of the code and the behaviour of the break statement – no. From this Draft C++17 Standard:
9.6.1 The break statement [stmt.break]
1 The break statement shall occur only in an iteration-statement or a
switchstatement and causes termination of the smallest enclosing iteration-statement orswitchstatement; control passes to the statement following the terminated statement, if any.
So, any 'extra' enclosing scopes (blocks delimited by { ... }) are irrelevant: the break will operate on the first switch (or iteration statement) the compiler finds in an 'outward search' from where it is placed. (Note that the same is true for a break statement inside the scope of an if block: that will still break out of the enclosing switch block or while/for loop.)