Muhammad
Muhammad

Reputation: 501

A switch statement without case: or default: labels

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.

Upvotes: 3

Views: 1306

Answers (2)

Asteroids With Wings
Asteroids With Wings

Reputation: 17454

Nothing happens.

[stmt.switch/5]: When the switch statement 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 the default label. If no case matches and if there is no default then 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.

Upvotes: 2

cigien
cigien

Reputation: 60258

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.

Upvotes: 4

Related Questions