C++

C++ : Lvaule and Rvalue

Lvalue and Rvalue

Every C++ expression yields an lvalue or an rvalue.

  • An Lvalue represents an object that has a memory address.
    In the below example, the string variable name has an identifiable address in memory.
    – An lvalue can be on the left side or on the right side of the assignment operator.
    In the below example, the variable name is on the left side ( name = “algotree.org” ) of assignment operator and on the right side ( same = name ).
    string name = "algotree"; // name is lvalue

    string same = name; // name and same are both lvalues.

    int sum = Add (42, 44); // Here sum is an lvalue
  • An Rvalue represents an object that does not have a memory address. Or simply put, an Rvalue is any object that is not an Lvalue.
    In the below program the constant “algotree” does not have an identifiable location in memory which makes it an rvalue.
    Similarly Add ( 42, 44 ) is an rvalue.
    – An rvalue can only be on the right side of the assignment operator.
    int Add (int x, int y) { return (x + y); } // ( x + y ) is an rvalue

    string name = "algotree"; // "algotree" is rvalue.

    int sum = Add (42, 44); // Add (42, 44) is an rvalue.

    // Below gives an error (assignment of read-only location β€˜"algotree"’) during compilation. 
    // "algotree" = name;

    object_1 = Object(); // Object() is an rvalue

Lvalue and Rvalue reference

Lvalue reference (Reference)

It T is a type, then T& is an lvalue reference to T.

In the below snippet, num is an lvalue and we are taking a reference of an lvalue in p.
Thus p is an lvalue reference.

int num = 5;
int& p = num; 

int& p = 42; // Error as 42 is an rvalue

const int& p = 42; // No error is reported, as constant lvalue reference can be assigned an rvalue.

Consider another example

int Square ( int& x ) { return x * x; }
int i = 5;
int p = Square ( i ); 
int q = Square ( 40 ); // Error [cannot bind non-const lvalue reference of type β€˜int&’ to an rvalue of type β€˜int’]

// To correct the error, we define the Square functions as below
int Square ( const int& x ) { return x * x; }

Rvalue reference

It T is a type, then T&& is an rvalue reference to T.
Rvalue references feature was added with the C++11 standard.

Consider the below example.

int Square ( int&& x ) { return x * x; } // Takes an rvalue reference as a parameter.
int Square ( int& x ) { return x * x; } // Takes an lvalue reference as a parameter.

int p = Square ( 5 ); // Calls Square ( int&& x )
int n = 5; 
int q = Square ( n ); // Calls Square ( int& x )


Copyright (c) 2019-2024, Algotree.org.
All rights reserved.