0

I'm curious about inserting the break inside a brackets in a case.

  int a = 1;
    switch (a)
    {
    case 1:
    {
        a = a;
        break;
    }
    a = a;
    case 2:
    {
        a = a;
        
    }
    break;
    }

In the C++ code above, in case 1 I've inserted the break inside the brackets, it is an error?

Is there any difference between case 1 and case 2 in the example above?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • This might help you: https://stackoverflow.com/questions/188461/switch-statement-fall-through-should-it-be-allowed – NathanOliver Oct 08 '21 at 12:53
  • Regarding the "is it an error" question, that can be very simply answered by trying it. If you build with extra warnings enabled, the compiler will definitely be able to tell you if it's syntactically correct or not, and very likely if there's any other possible problems. – Some programmer dude Oct 08 '21 at 12:55
  • 1
    Your C++ textbook should have an explanation, in one of its introductory chapters, how the `break` statement works, which should answer this question. Is there something ***specific*** in the explanation that's unclear? – Sam Varshavchik Oct 08 '21 at 12:59
  • You can also write `if (1 == 2) cout << "x";` it's obviously wrong but it's not a c++ error. The compiler will warn about this, usually at level 4 warning. – Barmak Shemirani Oct 08 '21 at 13:32

1 Answers1

4

Is there any difference between case 1 and case 2 in the example above?

In terms of the execution of the code and the behaviour of the break statement – no. From this Draft C++17 Standard:

9.6.1 The break statement        [stmt.break]

1    The break statement shall occur only in an iteration-statement or a switch statement and causes termination of the smallest enclosing iteration-statement or switch statement; control passes to the statement following the terminated statement, if any.

So, any 'extra' enclosing scopes (blocks delimited by { ... }) are irrelevant: the break will operate on the first switch (or iteration statement) the compiler finds in an 'outward search' from where it is placed. (Note that the same is true for a break statement inside the scope of an if block: that will still break out of the enclosing switch block or while/for loop.)

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83