7

Possible Duplicate:
Why can't variables be declared in a switch statement?
How can a variable be used when its definition is bypassed?

#include<stdio.h>
  int main()
  {
      int a=1;
      switch(a)
      {   int b=20;
          case 1: printf("b is %d\n",b);
                  break;
          default:printf("%d\n",b);
                  break;
      }
      return 0;
  }

ran on gcc 4.6.3, output not 20. What is going on here?

Community
  • 1
  • 1
Anon
  • 2,608
  • 6
  • 26
  • 38

5 Answers5

8

Initialization of variables inside switch statements is bad practice and undefined behavior.

  • But variable b is declared to be 20, compiler knows how much space variable b will take and what to store there. Why is the behavior undefined then? – Anon Jun 19 '12 at 12:58
  • @Anon: It's not part of a label. –  Jun 19 '12 at 13:00
6

The switch statement has this structure:

switch ( expression ){

    // declarations 

   case constant-expression : 
      ...
   case constant-expression : 
      ...
   default :
      ...
}

The declarations section is used at compile time to declare variables, but not used at run time to initialize them (no statements in that section are executed, in fact). Not the difference between declaring and initializing a variable. Since b is never intialized your code has the same result as:

int main(){
    int b;
    printf("b is %d\n", b);

    return 0;
}

Which is clearly undefined. Compiling with the -Wall flag will catch that you are using an uninitialized value.

Paul
  • 139,544
  • 27
  • 275
  • 264
5

If you turn up your compiler warnings you'll see:

warning: ‘b’ may be used uninitialized in this function

That's not a valid spot to initialise b, and therefore it contains uninitialised data at the time of printing instead of 20. You're causing undefined behaviour.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
0

The switch statement does a goto to the corresponding case statement based on the value of the switch variable and nothing more. Right now you're bypassing the initialization of b, so it'll print out whatever was in memory at the time at that location.

Hans Z
  • 4,664
  • 2
  • 27
  • 50
-2

Its a var scope issue. If you move

int b=20;

Outside the switch block, it will work.

Arcadien
  • 2,258
  • 16
  • 26