cppreference.com stats that the form of the switch statement is:
attr switch ( condition ) statement
and that statement is any statement.
So, what will happen if I didn't put any case: or default: labels in statement, as:
switch (1) {std::cout << 'x';}
What if I wrap a statement that doesn't come after any case: or default: label with additional braces as:
switch (1) {{std::cout << 'x';}}
since wrapping a declaration of a variable with additional braces will make that declaration legal even if it was before every case: and default: labels.
Yes, the grammar allows any statements inside a switch statement. So the following snippet:
switch( /* condition */ )
{
std::cout << "hello";
}
is perfectly valid, although useless, since statements inside a switch not preceded by a case or default label will never get executed.
As mentioned in the question, adding a scope inside a switch statement is needed if you want to declare a variable. However, this doesn't affect the above point. The following snippet:
switch( /* condition */ )
{
{
std::cout << "hello";
}
}
doesn't execute the cout statement either.
Nothing happens.
[stmt.switch/5]:When theswitchstatement is executed, its condition is evaluated. If one of the case constants has the same value as the condition, control is passed to the statement following the matched case label. If no case constant matches the condition, and if there is a default label, control passes to the statement labeled by thedefaultlabel. If no case matches and if there is nodefaultthen none of the statements in the switch is executed.
You didn't label any of your statements with a case label, so none of them is labelled by a case label that matches the condition, so no statement is executed.
Remember: labels aren't flow constructs that go between statements: they're annotations for statements. In the case of switch and goto, they're merely places to jump to. That's it.
Though the common pattern and typesetting of a switch/case example has found place in convention and in textbooks, there's nothing in the language grammar that means you have to write them that way.
switch is just a conditional goto with an optional fallback ("default") case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With