Ternary conditional and assignment operator precedence

蹲街弑〆低调 提交于 2019-11-27 13:05:20

The operator precedence in the C/C++ language in not defined by a table or numbers, but by a grammar. Here is the grammar for conditional operator from C++0x draft chapter 5.16 Conditional operator [expr.cond]:

conditional-expression:
    logical-or-expression
    logical-or-expression ? expression : assignment-expression

The precedence table like this one is therefore correct when you use assignment on the left side of the doublecolon, but not when used on the right side. What is the reason for this asymmetry I have no idea. It may be a historical reason: in C the conditional result was not lvalue, therefore assigning something to it had no sense, and allowing assignment to be accepted without parentheses might seem smart at that time.

The second line is equivalent to:

1 ? (j) : (k = 1);

That's the same as:

j;

That's the same as:

;

The key is that the two operands of the ternary conditional operator can be expressions, so operator precedence isn't relevant here. It's simply that the second operand is the assignment expression k = 1.

(1 ? j : k) = 1;

is equivalent to,

if(true) j = 1;
else k = 1;

And,

1 ? j : k = 1;

is equivalent to,

if(true) j;  // warning: statement has no effect
else k = 1;

In the second case,

1 ? j : k = 1;

is evaluated as:

(1) ? (j) : (k = 1);

and since one evaluates to true, the expression evaluates to j which does nothing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!