0
int flag = 0;
char a = 'b';
switch(a) {
  case 'a':
    cout << "In a";
    break;
  if(flag!=0) {
    case 'b':
      cout << "In b";
      break;
  }
  case 'c':
    cout << "In c";
    break;
  default:
    cout << "In d";
}

Can someone explain why the above code is printing "In b"? As per my understanding, it should print "In d"

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22

2 Answers2

2

Because a case 'a': is effectually a label to which the control flow is redirected at switch (a). In addition to not being able to modify compile-time structures, an if statement couldn't prevent this redirection simply because it is never reached in beforehand, as a result of aforementioned semantic.

Hi - I love SO
  • 615
  • 3
  • 14
2

the switch case mechanism is like goto call its jump to the relevant case if you will look at the assembly code here you will see that it translate to CMP and jmp or je command

ChrisMM
  • 8,448
  • 13
  • 29
  • 48
yaodav
  • 1,126
  • 12
  • 34