由於轉自轉載,作者不詳,在此表示感謝@作者
1.switch參數類型:
switch 後面的運算式不能跟double,float,long,String ,boolean,可以接int,short,byte,char!
2.switch中定義變數問題:
問題點:
switch (a)
{
case 1:
CString str="ABCDE"; //這句編譯有錯誤。請問為什嗎? =》在switch裡只能加{}來定義變數。
break;
case 2:
break;
....
}
回複1:
switch (a)
{
case 1:
{
CString str="ABCDE"; //OK
}
break;
case 2:
break;
....
}
加上花括弧就沒事了。這是因為如果a為2的話變數初始化語句將不被執行,
回複2:
switch 是一個單獨的程式段。而case(不加{})就不是一個單獨的程式段。看這個例子:
int j=1;
switch(j) {
case 1:int b;break;
case 2:b=1;break;
}
可以編譯。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:
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
}
}
回複3:
對於 switch (k)
{
case 1:
int i;
case 2:
i=0;
}
如果按照whjpn (常盤平) 的想法,那麼會有問題發生:
如果 k=1,則沒什麼
如果 k=2, 則i是誰定義的?這個問題怎麼解決?
所以對上述問題的修正辦法是:
1.在switch外聲明變數,這樣case 2就不會有錯誤了
2.在switch中聲明局部變數,局部變數的標誌是用{}
即:case 1:
{ int i; }
但是case 2就不能使用i了
另外
int k = 2;
switch(k)
{
case 0:
int i;//OK
int j = 1;//Error 不能定義,
break;
case 1:
{
int i = 1; //加了{},則可以定義,但是是局部變數
}
break;
case 2:
i = 2; //OK
diag_printf("kkkkkkkkkkkkkkkkkk:i=%d\n",i);
default: ;
}
在編譯時間,case 0的i被當作switch內的變數,所以儘管k=2,i仍然被賦值為2
即switch變數不能夠在case中聲明並賦值