开关语句是否关心案件订单?

发布于 2025-01-25 06:24:22 字数 457 浏览 4 评论 0原文

我有一个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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泅人 2025-02-01 06:24:22

我的问题是我必须按数字顺序进行?

不。

开关语句真的在乎...

不。

...我会因不顺序而失去性能吗?

不。

:-)

我会更好地分组它们,以便代码可以通过或使用goto case#?

取决于您的需求。

请记住,如果您不希望它们一起运行,则需要中断语句。

我要说的是,今天几乎所有编译器都足够聪明,可以优化switch语句。首先,使您的代码可读和可维护。后来,如果有性能瓶颈,并且开关是其中的一部分,请查看您可能拥有的其他选项。

My Question is do I have to go in numerical order?

No.

Does the switch statement actually care about that ...

No.

... will I loose performance by NOT going in order?

No.

:-)

Would I be better off grouping them so the code can fall through or using goto case#?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文