Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lvalue required as left operand of assignment

Tags:

Why am I getting

lvalue required as left operand of assignment 

with a single string comparison? How can I fix this in C?

if (strcmp("hello", "hello") = 0) 

Thanks!

like image 682
Joseph Avatar asked May 28 '11 15:05

Joseph


People also ask

What is meant by lvalue required in C?

The "l" stands for "left", as in the left hand side of the equals sign. An rvalue is the right hand value and produces a value, and cannot be assigned to directly. If you are getting "lvalue required" you have an expression that produces an rvalue when an lvalue is required.

What is left operand of assignment in C?

The left operand in all assignment expressions must be a modifiable lvalue. The type of the expression is the type of the left operand. The value of the expression is the value of the left operand after the assignment has completed. The result of an assignment expression is not an lvalue.

Why do we need lvalue required error in C?

This error occurs when we put constants on left hand side of = operator and variables on right hand side of it. Example 2: At line number 12, it will show an error L-value because arr++ means arr=arr+1. Now that is what their is difference in normal variable and array.


2 Answers

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)                              ^ 

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn't matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5; if (a = 0) // Always evaluated as false, no error. {     //... } 

vs.

int a = 5; if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue) {     //... } 

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

like image 129
MByD Avatar answered Sep 21 '22 17:09

MByD


You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0) 

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)                               ^ 

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

like image 43
EKons Avatar answered Sep 18 '22 17:09

EKons