【问题标题】:What would you expect of this C++ expression?您对这个 C++ 表达式有什么期望?
【发布时间】:2012-08-24 22:40:45
【问题描述】:
  bool bSwitch  = true;
  double dSum = 1 + bSwitch?1:2;

所以“dSum”是:

a)=1
b)=2
c)=3

结果太荒谬了,我为此受到了抨击......

我正在使用 VS2008 ->“Microsoft (R) 32-Bit C/C++-Optimierungscompiler Version 15.00.21022.08 für 80x86”

【问题讨论】:

  • 为了记录,每个 C++ 编译器都会这样做。经验法则:先乘除再加减;其他所有内容都有括号。
  • 自我注意:在处理三元运算符时,请使用尽可能多的括号。

标签: c++ visual-studio-2008 syntax ternary-operator


【解决方案1】:

这是一个优先的事情不是吗。

bool bSwitch  = true;
double dSum = (1 + bSwitch)?1:2;

dSum 将是 1.0

如果操作员周围有合理的间距,会更容易被发现。

【讨论】:

    【解决方案2】:

    operator+ 比三元运算符?: 具有更高的precedence

    所以,这等价于

    double dSum = ( 1 + bSwitch ) ? 1 : 2;
    

    因此,您拥有dSum == 1

    【讨论】:

    • 斯帕西博基里尔! Ja ponjal 4to oblagalsja ;-)
    【解决方案3】:

    我希望1.,因为+ 运算符优先于三元运算符。所以表达式被读作

    double dSum = (1 + bSwitch) ? 1:2;
    

    并且1 + bSwitch 不为零,因此它的计算结果为true

    operator precedence

    【讨论】:

      【解决方案4】:

      显然是一个警告,但我使用的是真正的编译器:

      void foo() {
        bool bSwitch  = true;
        double dSum = 1 + bSwitch?1:2;
      }
      

      给予:

      $ clang++ -fsyntax-only test.cpp
      test.cpp:3:28: warning: operator '?:' has lower precedence than '+'; '+' will be evaluated first [-Wparentheses]
        double dSum = 1 + bSwitch?1:2;
                      ~~~~~~~~~~~^
      test.cpp:3:28: note: place parentheses around the '+' expression to silence this warning
        double dSum = 1 + bSwitch?1:2;
                                 ^
                      (          )
      test.cpp:3:28: note: place parentheses around the '?:' expression to evaluate it first
        double dSum = 1 + bSwitch?1:2;
                                 ^
                          (          )
      1 warning generated.
      

      是的,我给出了整个命令行,默认情况下它开启

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        相关资源
        最近更新 更多