Can anyone explain the output of this C program?

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 %dn",b);
                  break;
          default:printf("%dn",b);
                  break;
      }
      return 0;
  }

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


在switch语句中初始化变量是不好的做法和未定义的行为。


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 %dn", b);

    return 0;
}

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


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.

链接地址: http://www.djcxy.com/p/14784.html

上一篇: 为什么我的开关盒有时需要在Objective中使用大括号

下一篇: 任何人都可以解释这个C程序的输出吗?