switch()的參數注意項

來源:互聯網
上載者:User

由於轉自轉載,作者不詳,在此表示感謝@作者

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中聲明並賦值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.