C++如果 switch 失败则内联

发布于 11-29 21:39 字数 417 浏览 6 评论 0原文

我刚刚发现内联 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;
}

[1] Benefits of inline functions in C++?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

南风起2024-12-06 21:39:18

这与switch无关。

10 + true ? 2 : 4

相当于:

(10 + true) ? 2 : 4.

如果你希望它的行为像:

10 + (true ? 2 : 4)

那么你需要这样写。

This is nothing to do with switch.

10 + true ? 2 : 4

is equivalent to:

(10 + true) ? 2 : 4.

If you want it to act like:

10 + (true ? 2 : 4)

then you will need to write it like that.

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