Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a case label in an if...else statement

Tags:

c++

G++ accepts this code and it behaves as I'd expect it to:

#include <cassert>

void example (int value, bool condition) {

  switch (value) {
  case 0:
    if (condition) {
  case 1:
      assert(condition || value == 1);
    } else {
      assert(!condition && value == 0);
    }
    assert(value == 0 || value == 1);
  }

}

int main () {
  example(0, false);
  example(1, false);
  example(0, true);
  example(1, true);
}

Maybe this is a silly basic question but, code smell aside, is it valid C++ to put a case label inside an if...else block, and will all well-behaved compilers correctly generate code that will jump over the else block when entered through case 1?

like image 923
Jason C Avatar asked Apr 01 '14 00:04

Jason C


1 Answers

As far as C++ is concerned (draft N3936):

  • case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels.
  • Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required.(§ 6.4.2 - 6)
  • It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. (§ 6.7 - 3)

What you are doing is technically ok, of course that doesn't mean you should.

like image 186
user657267 Avatar answered Nov 03 '22 12:11

user657267