Tutorial :C++: Short question regarding switch and break



Question:

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 }?


Solution:1

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".


Solution:2

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).


Solution:3

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


Solution:4

Think of break in this case as a goto end_of_switch.


Solution:5

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.


Solution:6

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).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »