为什么三元运算符中的多个语句不执行

Why are multiple statements in ternary operator not executed

我对以下问题感到困惑:

#include <iostream>

int main()
{
  bool a = true;
  int nb = 1;
  int nb2 = 2;
  a ? nb++, nb2++ : nb--, nb2--;
  std::cout << " (nb,nb2) = (" << nb << "," << nb2 << ")";
}

结果:

(nb,nb2) = (2,2) 

为什么 nb2 不等于 3

使用括号:

a ? (nb++, nb2++) : (nb--, nb2--);

原因:词法分析

因为运营商优先。您的表达式计算为

((a) ? (nb++, nb2++) : nb--), nb2--;

运算符, (comma) 是最后要处理的东西。这个例子根本不会编译但是

The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized.

详情见C++ Operator Precedence

这是预期的行为。

编译器将您的表达式理解为:

((a) ? (nb++, nb2++) : nb--), nb2--;

有关详细信息,请参阅: