Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

local scope in a switch statement - where do we break? [duplicate]

Possible Duplicate:
‘break’ statement when using curly braces in switch-case

While merging a package I came across this statement

switch (a)
{

case 1:
    {
        string str = "a is 1";
        cout << str << endl;
    }
    break;
case 2: ...
...

}

my question is does it matter if I place the break inside or outside the scope in case 1? here they place outside. I tried this and didn't see any difference. It makes sense to me that there is no difference but the guy with the PHD from my team said he remembers that there might be a difference but he can't remember what it is..

like image 363
Digital Da Avatar asked Aug 23 '12 17:08

Digital Da


People also ask

What break keywords do in switch statements?

You can use the break statement to end processing of a particular labeled statement within the switch statement. It branches to the end of the switch statement. Without break , the program continues to the next labeled statement, executing the statements until a break or the end of the statement is reached.

Does Break work for switch statement?

In a switch statement, the break statement causes the program to execute the next statement outside the switch statement. Without a break statement, every statement from the matched case label to the end of the switch statement, including the default clause, is executed.

How do you repeat a switch statement in C++?

One option is to set up a boolean value and if the default case is reached set it to true to repeat. bool repeat; do { repeat = false; //switch statement switch { default: repeat = true; } while(repeat); You could appropriately use repeat to know which question you would like to repeat as well. Save this answer.

What is a switch () statement?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.


2 Answers

There is no difference whether you put the break inside or outside the scope.

like image 168
Mark Byers Avatar answered Sep 24 '22 18:09

Mark Byers


A break reached inside a switchblock causes the next statment outside this switch block to execute. Therefore, it does not matter where you place the break, inside or outside the scope.

like image 43
eversor Avatar answered Sep 23 '22 18:09

eversor