开关盒的多种情况?

时间:2011-12-27 11:23:52

标签: c++ loops switch-statement

我可以使用开关盒来检查多种情况吗?例如,无论是其中任何一个条件还是满足条件,它都会做到这一点?

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

4 个答案:

答案 0 :(得分:22)

显然,如果条件A或条件B为true,如何执行代码的问题可以通过if( conditionA || conditionB )轻松回答,无需switch语句。如果switch声明由于某种原因是必须的,那么通过建议case标签可以通过其他答案之一来解决问题,可以再次轻易回答这个问题。

我不知道OP的需求是否完全由这些琐碎的答案所涵盖,但是除了OP之外,很多人都会阅读这个问题,所以我想提出一个更通用的解决方案来解决许多类似的问题琐碎的答案根本不会做。

如何使用单个switch语句同时检查任意数量的布尔条件的值。

这很hacky,但它可能会派上用场。

诀窍是将每个条件的true / false值转换为一位,将这些位连接成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. } 标签。例如:

{{1}}

答案 1 :(得分:16)

没有。在c ++中,switch case只能用于检查一个变量的值是否相等:

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

但您可以使用多个开关:

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

答案 2 :(得分: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;
}

答案 3 :(得分:2)

回应你的评论: 好的,我确实希望我的机器人在单击按钮1或2时向前移动。但不知何故,其他按钮只会遵循先前执行的方向。

您可以简单地和AND一起点击第一个按钮是否单击第二个按钮,然后使用单个switch case或if语句。

相关问题