Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this code involving the ternary operator getting an error in C, but not in C++? [duplicate]

Tags:

c++

c

I get "error: lvalue required as left operand of assignment" for "x=k" in C, but the code runs without an error in C++. I don't understand why C is giving me this error, while C++ doesn't.

#include <stdio.h>
int main() { 
    int j=10, k=50, x;
    j<k ? x=j : x=k; 
    printf("%d",x);
}
like image 526
starnairrr Avatar asked Sep 11 '25 06:09

starnairrr


1 Answers

In C, the ternary operator ?: has higher precedence than the assignment operator =. So this:

j<k ? x=j : x=k;

Parses as this:

((j<k) ? (x=j) : x)=k;

This is an error in C because the result of the ternary operator is not an lvalue, i.e. it does not denote an object and so can't appear on the left side of an assignment.

C++ however has ?: and = at the same precedence level, so it parses the expression like this:

j<k ? x=j : (x=k);

Which is why it works in C++. And actually, C++ does allow the result of the ternary operator to be an lvalue, so something like this:

(j<k ? a : b ) = k;

Is legal in C++.

You'll need to add parenthesis to get the grouping you want:

j<k ? x=j : (x=k);

Or better yet:

x = j<k ? j : k;
like image 75
dbush Avatar answered Sep 13 '25 20:09

dbush