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);
}
>Solution :
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 does allow the result of this operator to be an lvalue, and the ?: and = operators have the same precedence level, which is why it works in C++.
What you actually wanted is:
j<k ? x=j : (x=k);
(Which is how C++ parses the expression)
Or better yet:
x = j<k ? j : k;