Question

I was trying to understand the working of switch in C, and after browsing through some of the answers on SO, I fumbled upon the following piece of answer on SO :-

Basically, a switch acts like a goto to the appropriate label -- intervening statements aren't executed. Variable definitions (which actually happen at compile time) do happen, but if they contain initialization, that's skipped too.

How does switch statement work?

Can anybody please explain the meaning of this statement or provide some more insight into the working of switch.
`

Was it helpful?

Solution

Here is an example of a switch statement, directly copied from this answer.

#include <stdio.h>

int main(){
    int expr = 1;
    switch (expr)
    {
        int i = 4;
        f(i);
        case 0:
        i = 17;
        /* falls through into default code */
        default:
        printf("%d\n", i);
    }
}

Here is an equivalent code sample, written with goto.

#include <stdio.h>

int main(){
    int expr = 1;
    if (expr == 0) goto label0;
    else goto label1;

    int i = 4;
    f(i);
    label0:
    i = 17;

    label1:
    printf("%d\n", i);
}

Observe that, in both cases, when expr is initialized to 1, the initialization statement int i = 4 is not executed, so i is not initialized. However, i is defined, just as the quote in the question mentions.

OTHER TIPS

Without switch:

  if(1 == x)
     goto LABEL_A;
  else if(2 == x)
     goto LABEL_B;
  else if(10 == x)
     goto LABEL_C;
  else
     goto LABEL_D;

LABEL_A:
  /* Do A */;
  goto BREAK;

LABEL_B:
  /* Do B */;
  goto BREAK;

LABEL_C:
  /* Do C */;
  goto BREAK;

LABEL_D:
  /* Do D */;
  goto BREAK;

BREAK:

With switch:

switch(x)
  {
  case 1:
     /* Do A */;
     break;

  case 2:
     /* Do B */;
     break;

  case 10:
     /* Do C */;
     break;

  default:
     /* Do D */;
     break;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top