switch case 中的多个条件?
我可以使用 switch case 来检查多个条件吗?例如,满足条件中的任何一个都会执行其情况?
switch (conditionA or conditionB fullfilled)
{ //execute code }
Can i use switch case to check multiple condition? like for example either or of the condition fulfilled it will do its case?
switch (conditionA or conditionB fullfilled)
{ //execute code }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
显然,如果条件A或条件B为
true
,如何执行代码的问题可以用if(conditionA ||conditionB)
简单地回答,没有switch
code> 声明必要。如果出于某种原因switch
语句是必须具备的,那么可以通过建议case
标签失败来再次简单地回答这个问题,作为其他答案之一做。我不知道这些琐碎的答案是否完全涵盖了OP的需求,但是除了OP之外,还有很多人会阅读这个问题,所以我想提出一个更通用的解决方案,可以解决许多类似的问题,而这些问题是微不足道的答案根本行不通。
如何使用单个
switch
语句同时检查任意数量的布尔条件的值。这很hacky,但是它可能会派上用场。
诀窍是将每个条件的
true
/false
值转换为一个位,将这些位连接成一个int
值,然后switch
上的int
值。下面是一些示例代码:
然后,如果您有非此即彼的场景,则可以使用
case
标签失败。例如:。
Obviously, the question of how to execute code if either conditionA or conditionB is
true
can be trivially answered withif( conditionA || conditionB )
, noswitch
statement necessary. And if aswitch
statement is for some reason a must-have, then the question can again be trivially answered by suggesting acase
label fall through, as one of the other answers does.I do not know whether the needs of the OP are fully covered by these trivial answers, but this question will be read by many people besides the OP, so I would like to present a more general solution which can solve many similar problems for which trivial answers simply won't do.
How to use a single
switch
statement to check the values of an arbitrary number of boolean conditions all at the same time.It is hacky, but it may come in handy.
The trick is to convert the
true
/false
value of each of your conditions to a bit, concatenate these bits into anint
value, and thenswitch
on theint
value.Here is some example code:
Then, you can use
case
label fall through if you have either-or scenarios. For example:.
不可以。在 C++ 中 switch case 只能用于检查一个变量的值是否相等:
但您可以使用多个开关:
No. In c++ switch case can be used only for checking values of one variable for equality:
But you can use multiple switches:
switch/case 结构的跌落特性怎么样?
What about the fall-through feature of the switch/case construct?
回复您的评论:
好吧,我实际上希望我的机器人在单击按钮 1 或 2 时向前移动。但不知何故,其他按钮将仅遵循先前执行的先前方向。
您可以简单地将是否单击第一个按钮与是否单击第二个按钮组合在一起,然后使用单个 switch case 或 if 语句。
In response to your comment:
Ok I actually want my robot to move forward when either button 1 or 2 is clicked. But somehow the other buttons will just follow the previous direction previously executed.
You could simply AND together whether the first button is clicked with whether the second button is clicked, then use a single switch case or if statement.