开关箱多工况

Multiple conditions in switch case?

本文关键字:开关箱      更新时间:2023-10-16

我可以使用开关箱检查多个条件吗?比如,满足条件中的任何一个它会做它的情况吗?

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

显然,如果条件a或条件b是true,如何执行代码的问题可以简单地用if( conditionA || conditionB )来回答,不需要switch语句。如果switch语句出于某种原因是必须有的,那么可以通过建议case标签忽略来回答这个问题,正如其他答案之一所做的那样。

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

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

它很粗糙,但可能会派上用场。

技巧是将每个条件的true/false值转换为一个位,将这些位连接成int值,然后在int值上连接switch

下面是一些示例代码:
#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.
}

.

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

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

但是你可以使用多个开关:

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

switch/case结构的漏穿特性如何?

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时向前移动。但不知何故,其他按钮将遵循先前执行的方向。

您可以简单地将第一个按钮是否被单击与第二个按钮是否被单击放在一起,然后使用单个switch case或if语句。