How Do while inside switch statement works in c

155 views Asked by At

I have a code snippet where a do while statement is inside switch condition of case0, by default the case value is case1 but it seems executing case0. The output of the program print is 6. How is this possible, can someone explain the flow of code here. Thanks in advance for your answers.

int main()
{
    int a = 1, t =0,n=2;
    switch(a)
    {
        case 0:
        do
        {
        t++;
        case 4:t++;
        case 3:t++;
        case 2:t++;
        case 1:t++;
        }while(--n>0);
        printf("%d",t);
        
    }
    return(0);
    
}

3

There are 3 answers

0
molbdnilo On BEST ANSWER

Switch cases are similar to labels for goto.
You start at case 1, which is inside the loop – effectively using that as your starting point – and then execute the loop normally while "falling through" the cases as you go.

Here is the equivalent using goto:

int main()
{
    int a = 1, t =0,n=2;
    if (a == 0)
        goto case_0;
    if (a == 1)
        goto case_1;
    if (a == 2)
        goto case_2;
    if (a == 3)
        goto case_3;
    if (a == 4)
        goto case_4;
            
  case_0:
    do {
      t++;
  case_4:
      t++;
  case_3:
      t++;
  case_2:
      t++;
  case_1:
      t++;
    } while (--n > 0);
    
    printf("%d",t);
}

(The actual generated code might use a jump table rather than a series of conditionals, but the behaviour is the same.)

0
Jarod42 On

This is known at Duff's device.

case are mostly only label.

0
Tobias Fendin On

Since a is 1 in the beginning, case 1 will be executed. Then the loop condition is satisfied, thus it will loop again and execute t++; and all other cases until it tests the loop condition again and breaks the loop.

To get out of the switch, use the break command before every case.