开发者

C++: Short question regarding switch and break

Example:

switch( x )
{
case y:
 if ( true )
 {
    break;
 }
 cout << "Oop开发者_运维百科s";
 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 }?


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


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


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


Think of break in this case as a goto end_of_switch.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜