-4
#include <stdio.h>
int main(void) {
    int a = 1;
    switch(a) {
        int i = 2;
        case 1: printf("%d",i);
                break;
        default: printf("Hello\n");
    }
}

The following code sample is giving 36 as the output. How is this possible? I understand that the compiler will transfer the control to case 1 directly, without evaluating i. But, why am I getting the output as 36?

PS: I am using GCC.

Karthik Bhat
  • 361
  • 1
  • 4
  • 11

1 Answers1

4

In C++ this code is ill-formed because you cannot jump into the scope of a variable.

In C the code is undefined behaviour: int i; inside the switch block exists, however by jumping to case 1: you bypassed the part where the value 2 would have been assigned to i. So in fact you are attempting to print an uninitialized variable.

M.M
  • 138,810
  • 21
  • 208
  • 365