开关箱多工况
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语句。
相关文章:
- 既然存在危险,为什么项目要使用-I include开关
- 为什么这个音频包络不能通过开关的情况?
- 有人知道为什么在开关中使用stoi函数会返回恒定的错误吗
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 在 c++ 中在开关情况下使用和不使用"break"时的不同输出
- 为什么我的开关/机箱在使用枚举时默认?
- 为什么布尔开关语句有编译器警告?
- 如何使用"equal to"以外的评估编写开关语句
- 为什么开关的优化方式与 c/c++ 中的链接不同?
- 无法找到简单的开关大小写枚举错误
- QT编程中的非初始化开关箱错误
- 如何拆除这种开关箱
- 开关箱多工况
- 开关箱中的局部作用域
- int开关箱的问题
- 开关箱运行时类型检查
- 开关箱中"case"常量是否有变量类型?
- 开关箱如何处理"case"中的常量值?
- 开关箱尺寸动态变化
- 多开关箱设计模式