lvalue and rvalue in C++
Hello everyone, today we are going to learn about lvalue and rvalue in C++. lvalue and rvalue are among those topics in C or C++ which even some advanced or professional programmers don’t know and these topics are a little bit complex to understand also.
So, what are lvalue and rvalue?
L-value: lvalue refers to an identifiable memory location. This identifiable memory location identifies an object or a variable. Since lvalue is a memory location so, an lvalue object can appear on both sides of the assignment ‘=’ operator. Here are some examples of lvalue:
int val = 5; //here val is an lvalue object int val1 = val; //lvalue object(s) can also appear on the right side of '='
Now, we’ll talk about rvalue.
R-value: rvalue is a constant data that is stored at some memory location. Unlike an lvalue object, an rvalue object can appear on the right side of assignment ‘=’ operator i.e an rvalue object can’t be changed or reassigned. Here are some examples of rvalue:
int val = 1; //here 1 is an rvalue object 1 = val; //this statement gives compilation error //since 1 is a constant value so, it can't be changed or reassigned //and that's why an rvalue object never appears on the left side of '='
Some more examples of rvalue:
int a = 5, b; //here a and b are lvalue objects, 5 is an rvalue object b = a + 2; //this is a valid statement
But, if we switch the operands i.e
a + 2 = b //this statement gives error "Expression is not assignable"
Using address of ‘&’ operator with L-value and R-value
The address of ‘&’ operator can only be used with lvalue object(s) and not with rvalue object(s). For example:
int t = 5; // here t is an lvalue object int add = &t; //this is a valid statement
But, if we replace ‘t’ with an rvalue object i.e
int add1 = &2; \\this gives an error "Cannot take the address of an rvalue" int add2 = &(a+2); \\this also gives an error "Cannot take the address of an rvalue"
So, this was all about lvalue and rvalue. Hope you were able to understand the difference between lvalue and rvalue.
Have a great day ahead 🙂
Also read: C++ String find() function