2011-12-27 178 views
11

我可以使用開關的情況下檢查多個條件?例如任何一方或滿足條件的情況都會如此呢?開關情況下的多種情況?

switch (conditionA or conditionB fullfilled) 
    { //execute code } 
+4

* *開關*優於普通* if *的優點?如果可能的話,你能舉一個例子說明你會用它做什麼? – 2011-12-27 11:28:52

+0

好的,我確實希望我的機器人在單擊按鈕1或2時向前移動。但不知何故,其他按鈕將按照先前執行的方向。 – user982209 2011-12-27 12:11:59

回答

14

號在C++切換情況下,可以僅用於檢查一個變量的值是否相等:

switch (var) { 
    case value1: /* ... */ break; 
    case value2: /* ... */ break; 
    /* ... */ 
} 

但是可以使用多個開關:

switch (var1) { 
    case value1_1: 
     switch (var2) { 
      /* ... */ 
     } 
     break; 
    /* ... */ 
} 
19

顯然,如何如果任conditionA或conditionB是true執行代碼的問題都可以用平凡回答if(conditionA || conditionB),沒有switch聲明必要的。如果一個switch語句是出於某種原因必須具備的,那麼問題就可以再次通過平凡提示有case標籤告吹,因爲其他答案的人做回答。

我不知道OP的需求是否完全被這些微不足道的答案所覆蓋,但這個問題會被OP以外的許多人閱讀,所以我想提出一個更通用的解決方案,可以解決許多類似問題微不足道的答案根本無法解決的問題。

如何使用單一switch語句來檢查的布爾條件任意數量的值都在同一時間。

這是哈克,但它可能會派上用場。

訣竅是您的每一個條件的true/false值轉換爲位,串聯這些位爲int值,然後switchint值。

下面是一些示例代碼:

#define A_BIT (1 << 0) 
#define B_BIT (1 << 1) 
#define C_BIT (1 << 2) 

switch((conditionA? A_BIT : 0) | (conditionB? B_BIT : 0) | (conditionC? C_BIT : 0)) 
{ 
    case 0:      //none of the conditions holds true. 
    case A_BIT:     //condition A is true, everything else is false. 
    case B_BIT:     //condition B is true, everything else is false. 
    case A_BIT + B_BIT:   //conditions A and B are true, C is false. 
    case C_BIT:     //condition C is true, everything else is false. 
    case A_BIT + C_BIT:   //conditions A and C are true, B is false. 
    case B_BIT + C_BIT:   //conditions B and C are true, A is false. 
    case A_BIT + B_BIT + C_BIT: //all conditions are true. 
    default: assert(FALSE); //something went wrong with the bits. 
} 

然後,您可以使用case標籤告吹,如果你有非此即彼的場景。例如:

switch((conditionA? A_BIT : 0) | (conditionB? B_BIT : 0) | (conditionC? C_BIT : 0)) 
{ 
    case 0: 
     //none of the conditions is true. 
     break; 
    case A_BIT: 
    case B_BIT: 
    case A_BIT + B_BIT: 
     //(either conditionA or conditionB is true,) and conditionC is false. 
     break; 
    case C_BIT: 
     //condition C is true, everything else is false. 
     break; 
    case A_BIT + C_BIT: 
    case B_BIT + C_BIT: 
    case A_BIT + B_BIT + C_BIT: 
     //(either conditionA or conditionB is true,) and conditionC is true. 
     break; 
    default: assert(FALSE); //something went wrong with the bits. 
} 

8

怎麼樣的落式通過開關/案例結構的功能?

switch(condition){ 
    case case1: 
     // do action for case1 
     break; 
    case case2: 
    case case3: 
     // do common action for cases 2 and 3 
     break; 
    default: 
     break; 
} 
2

在回答您的評論: 好吧其實我是想點擊任一按鈕1或2,當我的機器人向前移動。但不知何故,其他按鈕將按照先前執行的方向。

無論點擊第一個按鈕還是單擊第二個按鈕,然後使用單個開關案例或語句,您都可以簡單地將它們放在一起。