I'm confused about the precedence of the direct assignment operator and the ternary conditional operator:
#include<stdio.h>
int main(void)
{
int j, k;
j = k = 0;
(1 ? j : k) = 1; // primero
printf("%d %d\n", j, k);
j = k = 0;
1 ? j : k = 1; // segundo
printf("%d %d\n", j, k);
return 0;
}
I expected the output to be:
1 0
1 0
But it turns out to be:
1 0
0 0
And I get this build notice:
main.cpp:20: warning: statement has no effect
Which is about the commented line as second.
Since the assignment operator has lower precedence than the ternary conditional operator, I expected the first and second commented lines to be equivalent. But it turns out not.
I have tried with g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
This question is a translation of the English original that I asked myself.
Operator precedence in the C/C++ languages is not defined by a table or by numbers, but by a grammar. Here is the grammar for the conditional operator from the C++0x draft chapter 5.16 Conditional operator [expr.cond] :
This precedence table as it was a few years ago is therefore correct when the assignment operator is used on the left side of the colon, but not when used on the right side. What is the reason for this asymmetry I do not know. It may be for historical reasons: in C the conditional result was not an lvalue, so assigning something to it made no sense, and allowing assignment to be accepted without parentheses may have seemed like a good idea at the time.
Today that table is already corrected and is correct in all cases.
This answer is a translation of the original in English written by Suma