By Danny Kalev
The programming language C++ inherited the convention that
allows for distinction between an r-value
and an l-value. Understanding what
these concepts mean will help you avoid common pitfalls and decipher cryptic
compilation errors.
The definition of values
An object is basically a region of memory storage. An l-value is an expression that refers to
such an object. The original definition of an l-value was “an object that can appear on the left-hand side
of an assignment”. However, this historical definition isn’t accurate
because const objects, which are l-values, cannot appear on the left-hand
side of an assignment.
An expression that can appear only on the right-hand side of
an expression is an r-value. The
following example contains instances of l-values
and r-values:
#include <string>
using namespace std;
int& f();
void func()
{
int n;
char buf[2]; //buf is an r-value
buf[0]= ‘a’; // ‘buf[0]’ is an l-value, ‘a’ is an r-value
n=7; // n is an l-value; the literal 7 is an r-value
string s1=”a”, s2=”b”, s3=”c”; // “a”, “b”, “c” are r-values
s1=string(“a”); // temporaries are r-values
int* p=new int; // p is an l-value; ‘new int’ is an r-value
f()=9; //a function call returning a reference is an l-value
s1.size(); //otherwise, a function call is an r-value
}
An l-value can
appear in a context that requires an r-value.
In this case, the l-value is
implicitly converted to an r-value. However,
you cannot place an r-value in a
context that requires an l-value.
Practical application
The distinction between an l-value and an r-value can
be used for eliminating a common bug. Programmers who mistakenly replace the = operator for the == operator can reverse the order of an equality expression,
placing the r-value on the left, like
this:
if (0==x) //instead of x==0
When placing the r-value
on the left, mistyping the == operator
as the = operator triggers a
compilation error:
if (0=x) // error: “L-value required”
Although this isn’t the most intelligible error message, it
certainly catches the bug.
Danny Kalev is a
systems analyst and software engineer with 14 years of experience, specializing
in C++ and object-oriented design.