Posted on 2011-04-28 14:51
點點滴滴 閱讀(439)
評論(0) 編輯 收藏 引用
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
}
}
在VC中使用switch語句時遇到“error C2360: initialization of 'k' is skipped by 'case' label”的編譯錯誤。
msdn有下面的說明:
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:
在switch語句內定義一個變量的時候,如果不在一個語句塊內,它是直到遇到switch的"}"才結束的。int i = 1;錯誤,錯就錯在它是以switch的"}"結束的,此時被case 1:語句跳過。int j = 1;它是遇到下面的"}"就結束了,因此正確。int k = 1;它雖然沒有在一個語句塊中,但它的下一個結束"}"正好就是switch的"}",不會被跳過,因此也正確。
所以,如果有在case內定義新變量,最好將該條case內的語句加上{}構成語句塊,避免出錯。
總之而言:在case里面聲明變量要用{}進行作用域限制。