开关语句是否关心案件订单?
我有一个Arduino Pro Micro,它将在循环中阅读4个引脚的状态,然后使用该引脚来评估开关语句,即
int bob = DigitalRead(1)+(DigitalRead(2)*2)+(DigitalRead(3)*4)+(DigitalRead(4)*8)
switch (bob) {
case 1:
case 2:
.
.
.
case 15:
}
我的问题是我必须按数字顺序进行操作吗? Switch语句实际上是否在乎这一点,还是我会因不行而失去性能?我会更好地对它们进行分组,以便代码可以通过或使用goto case#?在几种情况下,我想执行一些常见的代码,因此我认为我可以将这些案例分组在一起,并且只有在上一个案例语句中将代码与中断结束时。
因此,我可以将案例4和5分组在一起,并将8和10分组在一起,或者将9和11分组在一起。
这是可能的还是看到10之前的10之前,请寻找9?
I have an Arduino Pro Micro that during a loop will read the state of 4 pins and then use that pins to evaluate a switch statement i.e.
int bob = DigitalRead(1)+(DigitalRead(2)*2)+(DigitalRead(3)*4)+(DigitalRead(4)*8)
switch (bob) {
case 1:
case 2:
.
.
.
case 15:
}
My Question is do I have to go in numerical order? Does the switch statement actually care about that or will I loose performance by NOT going in order? Would I be better off grouping them so the code can fall through or using goto case#? There are several cases where I want to have some common code executed so I was thinking I could group those cases together and only have the code with the break at the end of it in the last case statement.
So I could have cases 4 and 5 grouped together as well as 8 and 10 grouped together or 9 and 11 grouped together.
Is that possible or will it see 10 comes before 9 and quit looking for 9?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不。
不。
不。
:-)
取决于您的需求。
请记住,如果您不希望它们一起运行,则需要
中断
语句。我要说的是,今天几乎所有编译器都足够聪明,可以优化
switch
语句。首先,使您的代码可读和可维护。后来,如果有性能瓶颈,并且开关是其中的一部分,请查看您可能拥有的其他选项。No.
No.
No.
:-)
Depends on what you need.
Remember, you need a
break
statement between cases, if you do not want them to run together.I would say that practically all compilers today are smart enough to optimise
switch
statements. First, make your code readable and maintainable. Later, if there's a performance bottleneck, AND the switch is part of it, then see what other options you might have.