Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch case do while 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 was expecting output for above code to be 0, as case 1 and case 2 are inside a do while which is inside case 0. Switch is testing on value 1, so case 0 will never be executed and hence neither case 1 or 2.

value of n coming to be 4. Any explanation ?

like image 943
Sagrian Avatar asked Mar 19 '23 04:03

Sagrian


1 Answers

Your code jumps into the middle of a loop. From that point on, it ignores the cases of the switch statement, so it does n++, n++, check condition, loop, etc. It helps if you think of a case as a label, and switch as a 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);

Like your original code, this simply skips the part of the loop body before label1 (the puts), then continues as if it had entered the loop in the normal way.

like image 120
Fred Foo Avatar answered Mar 27 '23 11:03

Fred Foo