In C, the ternary operator ?:
has higher precedence than the assignment operator =
. So this:
j<k ? x=j : x=k;
Parses as this:
((j<k) ? (x=j) : x)=k;
This is an error in C because the result of the ternary operator is not an lvalue, i.e. it does not denote an object and so can't appear on the left side of an assignment.
C++ however has ?:
and =
at the same precedence level, so it parses the expression like this:
j<k ? x=j : (x=k);
Which is why it works in C++. And actually, C++ does allow the result of the ternary operator to be an lvalue, so something like this:
(j<k ? a : b ) = k;
Is legal in C++.
You'll need to add parenthesis to get the grouping you want:
j<k ? x=j : (x=k);
Or better yet:
x = j<k ? j : k;