Conditional operator differences between C and C++

The conditional operator in C++ can return an lvalue, whereas C does not allow for similar functionality. Hence, the following is legal in C++:

(true ? a : b) = 1;

To replicate this in C, you would have to resort to if/else, or deal with references directly:

*(true ? &a : &b) = 1;

Also in C++, ?: and = operators have equal precedence and group right-to-left, such that:

(true ? a = 1 : b = 2);

is valid C++ code, but will throw an error in C without parentheses around the last expression:

(true ? a = 1 : (b = 2));

Leave a Comment