What is l-value and r-value in C/C++ languages. What is the difference between the two?
The name l-value and r-value are given based on the side of assignment operator that an expression can come. For example:
int x; // x is l-value, 2 is r-value. x = 2; // y is used as l-value, x as r-value // (though it can be used as l-value also as shown above). int y = x; // ERROR. 2 does not have l-value //(and hence cannot appear on left side of assignment) 2 = x;
if ptr is an int * like below
int *ptr;
then *ptr is an l-value.
Any of the following C expressions can be l-value expressions:
If arr is an array, like below:
int arr[5];
then we can assign to arr[i] but arr itself cannot be changed.
arr[2] = 3; //OK arr = &intVar; // ERROR. Can't modify Array name.
So, arr can appear on the right side of assignment but not on the left side. Should we say arr is r-value? According to me:
YES.
But, Some authors also talk about “modifiable l-value” and “non-modifiable l-value”.
They say that literals (constants like 2, ‘A’, “Hello”, 4.5, etc.) are r-values. Array names and constant identifiers are non-modifiable l-values and variables (objects) are modifiable l-values. I leave the choice of terminologies to you.
Example:
// function returning an l-value int fun1(){ int x = 3; return x; } // function returning an r-value int * fun2(){ static int y = 2; return &y; } main() { fun1() = 5; // ERROR. fun1 returns an l-value *fun2() = 5; // OK. fun2 returns an l-value }
Note that an l-value expression can be equally complex (and may not necessarily be a simple variable/object).