Search code examples
cassignment-operatorconditional-operatorlvalue

"error: lvalue required as left operand of assignment" in conditional operator


I'm new to C and today I learnt "?" operator which is the short type of if-else statement. However, when I execute this code:

int b;
int x;
b=3<2?x=12:x=34;

I get an error "error: lvalue required as left operand of assignment". I don't understand why it happens. Process in my mind is that the program first assigns 34 to x, then it assigns value of x,which is 34, to b. On the other hand, I can use the statement as

int b;
int x;
b=3<2?x=12:(x=34);

without any errors. I looked to my book but nothing helped. Why can't I use the first statement? What is my computer trying to do? Thanks...


Solution

  • +1 for interesting question - it highlights two differences between C++ and C.

    (1) The evaluation rules for ternary expressions are different in C and C++

    C++ parses as follows

    logical-OR-expression ? expression : assignment-expression
    

    It is therefore parsing your statement by matching assignment-expression to x=34

    b = 3<2 ? x = 12 : (x = 34);
    

    But C parses like this

    logical-OR-expression ? expression : conditional-expression 
    

    x = 34 is not a conditional-expression so your statement gets parsed like

    b = (3<2 ? x = 12 : x) = 34;
    

    (2) The conditional operator in C++ can return an lvalue, whereas C cannot. Hence, the following is legal in C++ but not in C:

    b = (3<2 ? x = 12 : x) = 34;
    

    Verified on ideone.com for C and C++ compilers. See also these links Errors using ternary operator in c for diff between C and C++ ternary operator Conditional operator differences between C and C++ for diff in lvalue rules