use*_*209 12 c++ loops switch-statement
我可以使用开关盒来检查多种情况吗?例如,无论是其中任何一个条件还是满足条件,它都会做到这一点?
switch (conditionA or conditionB fullfilled)
{ //execute code }
Run Code Online (Sandbox Code Playgroud)
Mik*_*kis 23
显然,如果条件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.
}
Run Code Online (Sandbox Code Playgroud)
然后,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.
}
Run Code Online (Sandbox Code Playgroud)
.
cit*_*txx 16
不可以.在c ++中,switch case只能用于检查一个变量的值是否相等:
switch (var) {
case value1: /* ... */ break;
case value2: /* ... */ break;
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
但您可以使用多个开关:
switch (var1) {
case value1_1:
switch (var2) {
/* ... */
}
break;
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
Kon*_*tin 10
开关/外壳结构的跌落功能怎么样?
switch(condition){
case case1:
// do action for case1
break;
case case2:
case case3:
// do common action for cases 2 and 3
break;
default:
break;
}
Run Code Online (Sandbox Code Playgroud)