Actual use of conditional statement?

Consider the following code snippet:

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 stupid example, a conditional statement expression is a shortcut to:

if (i & 1) k = 99 - i; else m = 99 - i;

My compiler does not complain, and the execution of this part of the code gives the expected result

k: 98   m: 99

My question, however, is that this is valid code according to the C standard? I have never seen anything like it before.

+5
source share
3 answers

Footnote 110 of the C11 standard:

The conditional expression does not give an lvalue.

And 6.5.16 paragraph 2:

The assignment operator must have a mutable value of lvalue as its left operand.

No, this code is not compliant with C.

In C ++ 11, it is valid:

lvalues ​​ , lvalue.

, , C ++ . , , ++ " C", C; MSVC?

+8

C, , . :

*((i & 1) ? &k : &m) = 99 - i;

.

+4

lval ++, C.

++ (ISO-IEC 14882: 1998 (E) 5.16.4)

lvalues ​​ , lvalue.

C, :

ISO/IEC 9899: TC2, 6.5.14.6

If both the second and third operands are pointers, and one is a constant of a null pointer, and the other is a pointer, the result type is a pointer to a type qualified with all classifiers of type types pointed to by both operands.

*((i & 1) ? &k : &m) = 99 - i;
+1
source

All Articles