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.
Footnote 110 in the C11 standard:
And 6.5.16 paragraph 2:
So no, that code does not conform to the C standard.
In C++11, it is valid:
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?