显然,如果条件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.
}
.