Valid use of the conditional operator?
c, conditional-operator
Solution
Footnote 110 in the C11 standard:
A conditional expression does not yield an lvalue.
And 6.5.16 paragraph 2:
An assignment operator shall have a modifiable lvalue as its left operand.
So no, that code does not conform to the C standard.
In C++11, it is valid:
If the second and third operands are lvalues and have the same type, the result is of that type and is an lvalue.
So this is another one of those dusty corners where C and C++ differ significantly. If your compiler doesn't produce an error, then I'm guessing you're using a C++ compiler with a "C mode", rather than a proper C compiler; MSVC?
Problem
Consider the following piece of code: ``` int i, k, m; k = 12; m = 34; for (i = 0; i < 2; i++) ((i & 1) ? k : m) = 99 - i; printf("k: %ld m: %ld\n\n", k, m); ``` In this silly example, the conditional operator expression is a shortcut for: ``` if (i & 1) k = 99 - i; else m = 99 - i; ``` My compiler does not complain and executing this piece of code gives the expected output ``` k: 98 m: 99 ``` My question, though, is if this is valid code according to the C standard? I have never seen anything like it used before.