ajay
ajay

Reputation: 9680

Please explain the nested switch-case statements in the following C program and the corresponding output

On compiling and running the code below, we get the output as stated. Please explain the output. case 2 is nested in case 0 so the program shouldn't print anything at all.

#include <stdio.h>

int main() {
    int i=5;
    switch ( 2 ) {
        case 0:
            for (  i=0; i<10; i++ ) {
        case 1:
            printf("A i=%d\n",i);
        case 2:
            printf("B i*i=%d\n",i*i);
            };
        case 3:
            printf("done");
            break;
    }

    return 0;
}

/* OUTPUT
B i*i=25
A i=6
B i*i=36
A i=7
B i*i=49
A i=8
B i*i=64
A i=9
B i*i=81
done
*/

Upvotes: 1

Views: 2435

Answers (2)

user1646196
user1646196

Reputation: 588

        for (  i=0; i<10; i++ ) {
    case 1:
        printf("A i=%d\n",i);
    case 2:
        printf("B i*i=%d\n",i*i);
        };

So case 2 is inside the for loop, hence the repetition in the outputs. With a case you need to put in a break or it executes every case after the one it switches to.

switch(2)
case 1: //blah
case 2: //blah
case 3: //blah

For this example above the code in cases 2 and 3 are ran whereas normally you write:

switch(2)
case 1: //blah
    break;
case 2: //blah
    break;
case 3: //blah
    break;

In which case only case 2 is ran

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340346

The switch statement is just a jump into the middle of a for loop (at case label 2). Then the code executes the for loop. Pretty much equivalent to:

#include <stdio.h>

int main() {
    int i=5;

    goto label_2;

    for (  i=0; i<10; i++ ) {
        printf("A i=%d\n",i);
      label_2:
        printf("B i*i=%d\n",i*i);
    };

  label_3:
    printf("done");

    return 0;
}

That's all there is to it.

Upvotes: 7

Related Questions