Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this code getting an error in C, but not in 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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading