Search code examples
c++cswitch-statementdo-whileduffs-device

How Do while inside switch statement works in c


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);
    
}


Solution

  • 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.)