tags:

views:

138

answers:

6

Example:

switch( x )
{
case y:
 if ( true )
 {
    break;
 }
 cout << "Oops";
 break;
}

If the switch statement selects y, will Oops be written to the standard output? - Is break in switch statements a dynamic keyword like continue which can be called under conditions or static like a closing bracket }?

+1  A: 

No, Oops will not written out, the break jumps behind this statement.

You can use break statements conditionally just fine, you only have to watch out when you create nested statements that also support break (i.e. loops).

Georg Fritzsche
+10  A: 

break breaks out of an enclosing switch, while, for, or do ... while. It doesn't break out of an enclosing if or bare block. Pretty much exactly like continue.

It's certainly not part of the required syntax of a switch statement (like a close-brace is part of the syntax of blocks). break is a statement, essentially meaning "transfer execution to the point after the end of the innermost breakable construct".

Steve Jessop
A: 

break is absolutely dynamic. So, if you write if (false) break; your Oops would be written out.

Kotti
A: 

Think of break in this case as a goto end_of_switch.

djeidot
A: 

No, it will not be printed in your case. break only breaks from switches and loops, not conditionals or functions or arbitrary enclosing scopes. Therefore, a more relevant question would be whether Oops is printed in this case:

switch( x )
{
case y:
 for ( int i = 0; i < 10; ++i )
 {
    break;
 }
 cout << "Oops";
 break;
}

And the answer here is yes, it will. The break will break out of the for, not the switch.

Tyler McHenry
A: 

No. It would break out of the switch construct. "break" is used to come out of the innermost loop construct or switch construct. So, in your case the "oops" is not printed out on the screen. If you want that to happen, in your code, you could use if(false) instead of if(true).

mkamthan