Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lvalue required as unary ‘&’ operand

Tags:

c

pointers

I have the following lines of code :

#define PORT 9987

and

char *ptr = (char *)&PORT;

This seems to work in my server code. But as I wrote it in my client code, it gives this error message :

lvalue required as unary ‘&’ operand

What am I doing wrong?

like image 486
Indradhanush Gupta Avatar asked May 24 '13 03:05

Indradhanush Gupta


People also ask

What is lvalue required?

If you are getting "lvalue required" you have an expression that produces an rvalue when an lvalue is required. For example, a constant is an rvalue but not an lvalue. So: 1 = 2; // Not well formed, assigning to an rvalue int i; (i + 1) = 2; // Not well formed, assigning to an rvalue.

What is lvalue 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: #include <stdio.h> void main()

How do you fix lvalue required as left operand of assignment?

Best practice to avoid such mistakes in if conditions is to use constant value on left side of comparison, so even if you use "=" instead "==", constant being not lvalue will immediately give error and avoid accidental value assignment and causing false positive if condition.

What is lvalue in Arduino?

Which Arduino has a pin 60? In the C programming language, a lvalue is something you can assign a value to and an rvalue is a value that can be assigned. The names just mean 'left side of the equals' and 'right side of the equals'.


2 Answers

C preprocessor is at play here. After the code is preprocessed, this how it looks like.

char *ptr = (char *)&9987;

address of (&) operator can be applied to a variable and not a literal.

like image 108
Lazylabs Avatar answered Oct 12 '22 11:10

Lazylabs


The preprocessor macros have no memory and at compile time the macro is replaced with the value. So actualy thing happening here is char *ptr = (char *)&9987;, which is not possible.

like image 40
akhil Avatar answered Oct 12 '22 13:10

akhil