不知道C++的switch语句为什么这样设计
///copied from VC++6 Help:
Compiler Error C2360
--------------------
initialization of 'identifier ' is skipped by 'case ' label
The specified identifier initialization can be skipped in a switch statement.
It is illegal to jump past a declaration with an initializer unless the declaration is enclosed in a block.
The scope of the initialized variable lasts until the end of the switch statement unless it is declared in an enclosed block within the switch statement.
The following is an example of this error:
void func( void )
{
int x;
switch ( x )
{
case 0 :
int i = 1; // error, skipped by case 1
{ int j = 1; } // OK, initialized in enclosing block
case 1 :
int k = 1; // OK, initialization not skipped
}
}
看了还是不明白为什么要将int i = 1; 放在switch语句外面。其实我挺烦这样做的。为什么不能把i的作用域限定case 0 呢?不知道C++的switch语句为什么这样设计?
[解决办法]
void func( void )
{
int x;
switch ( x )
{
case 0 :
int i = 1; // error, skipped by case 1
{ int j = 1; } // OK, initialized in enclosing block
case 1 :
int k = 1; // OK, initialization not skipped
}
}
很明显,在上述代码中,int i=1;不在基于case 0:的作用域内。除非:
case 0:
{
int i = 1;
{ int j = 1; }
}
否则的话,它是在整个switch作用域中的。这时,如果发生这种情况:
case 0: int i = 1;
case 1: i++;
...
若case 0不成立而case 1成立,显然就会因为外部符号未定义(在运行时)而发生应用程序内部的致命错误。这时,编译器应该如何对待这个符号i呢?