Lvalue vs Rvalue in C

In this tutorial, we will explain the concept of Lvalue and Rvalue in the C programming language using simple terms.


Lvalue

An Lvalue refers to an object that can be modified and has storage space. Typically, a variable is considered an Lvalue because it can be changed and it has memory allocated for it.


Rvalue

An Rvalue refers to an object that cannot be modified and does not have any storage space. This means that the object does not have any memory associated with it. Examples of Rvalues include expressions like 3 + 4 or constants like 5. They cannot be modified and do not have storage capability.

It’s important to note that Lvalue and Rvalue are terms related to the left and right sides of an assignment expression. The Lvalue represents the requirement that the variable on the left side of the assignment statement must have storage capability. The Rvalue refers to the expression, function call, or constant on the right side of the assignment statement.

To better understand the difference, let’s consider the following example:

#include <stdio.h>

int main() {
   int a = 10;
   int b;
   b = a; // Valid
   10 = b; // Invalid
   return 0;
}

In the above program, the statements int a = 10; and b = a; are valid assignment statements because the Lvalues (a and b) can be modified. However, the statement 10 = b; is invalid because 10 is a constant, which is an Rvalue. Constants cannot be modified, and they do not have any memory associated with them.

It’s worth noting that an Lvalue can appear on the right side of an assignment expression as well. For example, in the statement b = a;, the variable a is an Lvalue.



Leave a comment

Leave a comment

Your email address will not be published. Required fields are marked *

Thank you for choosing to leave a comment. Please be aware that all comments are moderated in accordance with our policy. For more information, please review our comments policy. Rest assured that your email address will not be shared with anyone. Kindly refrain from using keywords in your comment. Let’s maintain a respectful atmosphere and engage in meaningful conversations.