Home > Back-end >  Switch case printing case when condition is not met
Switch case printing case when condition is not met

Time:11-01

I'm learning switch case, and I'm trying to understand the theory behind this code

int main() {

  int number = 7;

  switch(number) {
    case 6:
      printf("Charizard\n");
      break;
    case 7:
      printf("Squirtle");
    case 8:
      printf("Wartortle");
      break;
    case 9:
      printf("Blastoise");
      break;
    default:
      printf("Unknown\n");
      break;
  }
}

Output

SquirtleWartortle

Expected Output

Squirtle

I understand removing the break; in case 7 causes the code to continue checking for more cases until another break is met. But what I don't understand is why case 8 is printed, it shouldn't print since the condition is not met.

CodePudding user response:

The misunderstanding is here:

I understand removing the break; in case 7 causes the code to continue checking for more cases until another break is met.

The code does not actually check for more cases, it just executes all the cases below until a break is met.

CodePudding user response:

The condition in the switch statement is checked only once when its expression is evaluated. Then the control is passed to the corresponding case label or after the switch statement if the label default is absent.

So in your code the control is passed to the statement marked with the case label case 7: and then the code is executed sequentilly until the break statement is encountered

case 7:
  printf("Squirtle");
case 8:
  printf("Wartortle");
  break;

CodePudding user response:

case are labels , they take the control to that position , it will not do anything, since there is no break at the end of case 7 , the control flows through to next line and so on until it encounters break or end of the switch. Hence case 8 will also be printed.

  • Related