Search code examples
c++csyntaxternary-operatorlvalue

Ternary conditional operator on the left of assignment operator


I have a condition and three variables.

// Assume these variables are all initialized.
int *a;
int *b;
const int c;
const bool condition;

if (condition)
    *a = c;
else
    *b = c;

I want theif block to be on one line through a ternary conditional operator.

(condition ? *a : *b) = c;

I don't see why that's not allowed as I'm not breaking the rule of ternary conditional operators. Both *a and *b return the same type.


Solution

  • This is not allowed in C because *a is an int value after a pointer dereference and a conditional; is not an lvalue, i.e. not assignable. However, this is allowed:

    *(condition ? a : b) = c;
    

    Now that the conditional produces a pointer, and the dereference happens outside of it, the overall expression is an assignable lvalue.

    You can expand this to two conditions and three pointers:

    *(condition1 ? a : (condition2 ? b : c)) = d;