switch的意思用法

Home Home
引用 | 編輯 1234561231
2012-01-07 19:51
樓主
推文 x0
請問switc ..

訪客只能看到部份內容,免費 加入會員



獻花 x0
引用 | 編輯 kb041204
2012-01-07 22:02
1樓
  
// 其實switch 好像 if...elseif...else

switch(變數)
{ //記緊開括號!!
case 數值:
//如果變數是數值時要做的指令
break;

case 數值2:
//如果變數是數值2時要做的指令
break;

case 數值3:
//如果變數是數值3時要做的指令
break;

// 可以更多

default:
//如果變數不是以上全部的數值便要做的指令
break;

} //記緊關括號!!

獻花 x1
引用 | 編輯 ebolaman
2012-01-07 23:46
2樓
  
參考

http://caterpillar.onlyfun.net/Gossip/CppGossip/switchStatement.html






Switch 就是看例如 switch (a) 括號內的 a 的值 是什麼

然後就跑到底下 Case 中對應的數字,假如沒有對應的 case 會跑到 default

case N 很像是進入點,所以為什麼要加 break ? 因為不加 break 程式會繼續跑下去,底下的其他 case 中的東西也會被跑到,那就不是預期的結果了

我用兩張圖來表示



第一,沒有在 case 最後加入 break,會發生什麼事?




範例一:
複製程式
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;

    switch (a)
    {
    case 5:
        printf("5 is here\n");
    case 6:
        printf("6 is here\n");
    default:
        printf("default!!\n");
    }

    getchar();
}


就像溜滑梯一樣,程式判斷 a 是 5,然後就跑到 Case 5: 的進入點

接著就往下滑,case 6 和 default 都會跑到




第二,有加入 break;




範例二:
複製程式
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 5;

    switch (a)
    {
    case 5:
        printf("5 is here\n");
    break;
    case 6:
        printf("6 is here\n");
    break;
    default:
        printf("default!!\n");
    }

    getchar();
}


那麼跑完成 printf("5 is here\n"); 遇到 break; 就會跳出 switch 的結構

不過要不要加 break; 還是要看你要設計什麼

獻花 x1
引用 | 編輯 kb041204
2012-01-08 00:27
3樓
  
我加break是因為我寫程式的軟件不加break的話不知為何會繼續運行下去...

獻花 x0
引用 | 編輯 1234561231
2012-01-08 08:11
4樓
  
了解.另外問大家一個問題按鍵要怎綁定啊
要用到哪個語法

獻花 x0
引用 | 編輯 kb041204
2012-01-08 23:07
5樓
  
問題按鍵即是甚麼?

獻花 x0
引用 | 編輯 LASER10227
2012-01-13 17:33
6樓
  
補充:

若是你在switch statment中任一個case有做declare的話,

請記得每個case都要加上program block {}

例如...

switch(n)
{
  case 1:
          int i;
          ...
          break;

這樣compiler不會給你過,這所為的cross initialization
因為你宣告的所以變數,在下一個case時lifetime還是存在的,所以要記得
加上大括號{}

獻花 x0