C++如果 switch 失败则内联
我刚刚发现内联 if (A?B:C) 在 switch 语句中不能按预期工作。
其中 A 是布尔值,B 和 C 都是不等于 0 的整数。当放置在开关内时,该语句的结果是 0。
我找到了一篇 stackoverflow 帖子 [1],其中提到了这种行为,但我找不到任何解释为什么这不能按我的预期工作。是什么原因造成的?
例如:
int foo = 6;
switch(foo)
{
case 6:
return 10 + true ? 2 : 4;
}
[1] C++ 中内联函数的好处?
I just found out the hard way an inline if (A?B:C) does not work as expected in a switch statement.
where A a boolean, B and C both integer unequal to 0. The result of this statement is 0 when placed inside a switch.
I found a stackoverflow post [1] where this behaviour was mentioned but I can not find any explanation why this doesn't work as I would expect. What is causing this?
For example:
int foo = 6;
switch(foo)
{
case 6:
return 10 + true ? 2 : 4;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

这与
switch
无关。相当于:
如果你希望它的行为像:
那么你需要这样写。
This is nothing to do with
switch
.is equivalent to:
If you want it to act like:
then you will need to write it like that.