将 if 语句转换为 switch 语句
如何将以下 if= 语句转换为 switch 语句,而不需要为该区间 (41-49) 之间的每个数字创建一个案例?是否可以?
if (num < 50 && num > 40)
{
printf("correct!");
}
How can I convert the following if=statement to a switch-statement WITHOUT needing to create a case for every number between that interval (41-49)? Is it possible?
if (num < 50 && num > 40)
{
printf("correct!");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须枚举开关的每种情况。编译器将其转换为跳转表,因此您不能使用范围。但是,您可以让多个案例使用相同的代码块,这可能更接近您想要的。
You have to enumerate every case for a switch. The compiler converts this to a jump table, so you can't use ranges. You can, however, have multiple cases use the same block of code, which may be closer to what you want.
这又如何呢?
What about this?
它可能会导致多级决策网络......可怕吗?
It may result in multilevel decision networks.. scary?
在 C 或 C++ 中(因为您使用的是 printf,我假设它就是这样),需要为每个选择枚举案例。
switch/case
和if
之间的唯一区别是编译器可以将其转换为计算的 goto 而不是检查范围。如果switch/case
支持范围,那就违背了开启此优化可能性的目的。In C or C++ (since you are using printf, I'll assume that's what it is), cases need to be enumerated for each choice.
The only difference between
switch/case
andif
is the possibility that the compiler can turn it into a computed goto instead of checking ranges. Ifswitch/case
supported ranges, that would defeat the purpose of opening the possibility of this optimizaton.