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