Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
lvalue and rvalue in C
An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). An rvalue is defined by exclusion − every expression is either an lvalue or an rvalue, so an rvalue is an expression that does not represent an object occupying some identifiable location in memory.
Syntax
lvalue = rvalue; // Valid assignment rvalue = lvalue; // Invalid assignment (compilation error)
Example 1: Valid lvalue Assignment
An assignment expects an lvalue as its left operand. Here's a valid example −
#include <stdio.h>
int main() {
int i = 10; // i is lvalue, 10 is rvalue
int j;
j = i; // j is lvalue, i can be used as rvalue
printf("i = %d, j = %d<br>", i, j);
return 0;
}
i = 10, j = 10
Example 2: Invalid rvalue Assignment
This example shows what happens when we try to assign to an rvalue −
#include <stdio.h>
int main() {
int i = 5;
/* This would cause compilation error:
10 = i; // Error: lvalue required as left operand
*/
printf("i = %d<br>", i);
return 0;
}
i = 5
Example 3: lvalues and rvalues with Arrays
Array elements are lvalues, while array names used in expressions are rvalues −
#include <stdio.h>
int main() {
int arr[3] = {1, 2, 3};
arr[0] = 10; // arr[0] is lvalue
arr[1] = arr[0] + 5; // arr[1] is lvalue, arr[0]+5 is rvalue
printf("arr[0] = %d, arr[1] = %d<br>", arr[0], arr[1]);
return 0;
}
arr[0] = 10, arr[1] = 15
Example 4: Address Operator with lvalues
The address operator (&) can only be applied to lvalues −
#include <stdio.h>
int main() {
int x = 42;
int *ptr = &x; // &x is valid (x is lvalue)
/* This would cause compilation error:
int *ptr2 = &(x + 1); // Error: &(x+1) invalid (x+1 is rvalue)
*/
printf("x = %d, address = %p<br>", x, (void*)ptr);
return 0;
}
x = 42, address = 0x7fff5fbff6ac
Example 5: Function Return Values as rvalues
Function return values are typically rvalues and cannot be assigned to −
#include <stdio.h>
int getValue() {
return 100; // Returns an rvalue
}
int main() {
int x;
x = getValue(); // getValue() returns rvalue
/* This would cause compilation error:
getValue() = 50; // Error: cannot assign to rvalue
*/
printf("x = %d<br>", x);
return 0;
}
x = 100
Key Points
- lvalues have memory addresses and can appear on the left side of assignment operators.
- rvalues are temporary values that cannot be assigned to directly.
- Variable names, array elements, and dereferenced pointers are examples of lvalues.
- Literals, arithmetic expressions, and function return values are examples of rvalues.
Conclusion
Understanding lvalues and rvalues is fundamental in C programming as it determines what can be assigned to and what operations are valid. lvalues represent assignable memory locations, while rvalues represent temporary values.
