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);
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With