4
#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 ?

Sagrian
  • 1,048
  • 2
  • 11
  • 29

1 Answers1

7

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.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • @larsmans : With your explanation that case are label - wouldn't it cause problem for nested switch, if both outer and inner switch has same case statements. E.g. if I put following in case 0 switch (i) { case 1: printf("here1"); case 2: printf("here2"); } now label1 and label2 should conflict as they have a function scope. Please elaborate more on this. FYI - I don't get any error though for doing above. – Sagrian Oct 15 '14 at 16:46
  • 1
    @Sagrian: A `case ...:` label is associated with the nearest enclosing `switch` statement. There's no ambiguity. – Keith Thompson Oct 15 '14 at 17:16