Switch case to do during nesting

#include<stdio.h>
int main()
{
    int n=0, i=2;
    switch(1)
    {
    case 0:do
           {
    case 1: n++;
    case 2: n++;
           }while(--i > 0);
    }
    printf("n = %d",n);
}

I expected that the output for the above code would be 0, since case 1 and case 2 are inside do, and in the internal register 0. Switch tests the value 1, so case 0 will never be executed, and therefore, no case 1 or 2.

the value of n will be 4. Any explanation?

+4
source share
1 answer

Your code jumps to the middle of the loop. Since then, he ignores cases of a switch statement, so it performs n++, n++, checks the condition, cycle, etc. This helps if you are thinking about casehow to label and switchhow goto:

    int n=0, i=2;

    if (1 == 0)
        goto label0;
    else if (1 == 1)
        goto label1;
    else if (1 == 2)
        goto label2;

label0:
    do {
        puts("loop");
label1:
        n++;
label2:
        n++;
    } while (--i > 0);

, label1 (puts), , .

+7

All Articles