簡體   English   中英

開關盒的多種情況?

[英]Multiple conditions in switch case?

我可以使用開關盒來檢查多種情況嗎? 例如,無論是其中任何一個條件還是滿足條件,它都會做到這一點?

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

顯然,如果conditionA或conditionB為true ,如何執行代碼的問題可以通過if( conditionA || conditionB )來簡單地回答,不需要switch語句。 如果switch語句由於某種原因是必須的,那么通過建議case標簽可以通過其他答案之一來解決這個問題。

我不知道OP的需求是否完全由這些微不足道的答案所涵蓋,但是除了OP之外,很多人都會閱讀這個問題,所以我想提出一個更通用的解決方案,它可以解決許多類似的問題答案根本不會做。

如何使用單個switch語句同時檢查任意數量的布爾條件的值。

這很hacky,但它可能會派上用場。

訣竅是將每個條件的true / false值轉換為bit,將這些位連接成int值,然后switch int值。

這是一些示例代碼:

#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.
}

不可以。在c ++中,switch case只能用於檢查一個變量的值是否相等:

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

但您可以使用多個開關:

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

開關/外殼結構的跌落功能怎么樣?

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

回應你的評論:好的,我確實希望我的機器人在點擊按鈕1或2時向前移動。 但不知何故,其他按鈕將遵循之前執行的前一個方向。

您可以簡單地和AND一起點擊第一個按鈕是否單擊第二個按鈕,然后使用單個switch case或if語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM