What are lvalue and rvalue in C?

TL;DR: “lvalue” either means “expression which can be placed on the left-hand side of the assignment operator”, or means “expression which has a memory address”. “rvalue” is defined as “all other expressions”.

What does the following program do?

int foo() { return 4; }
int main(void) {
  foo() = 3;
  return 0;
}

The program doesn’t do anything because it doesn’t mean’t mean anything. It doesn’t make sense to assign a value to foo(). Function calls are one-way: domain in, range out. We can’t assign to a function’s range.

Thus, your C compiler will give you a compile error:

% clang test.c
test.c:3:9: error: expression is not assignable
  foo() = 3;
  ~~~~~ ^
1 error generated.

Clang tells me that the “expression is not assignable”. This seems clear, but other compilers will use different terminology, e.g. “need lvalue as target of assignment”.

This terminology, “lvalues” and “rvalues”, is talking about the same thing. The terminology derives from whether the value can/must be on the left or right of an assignment. In the BNF for C, we might write:

assignment_expr ::= lvalue "=" (lvalue | rvalue) ;
lvalue ::= var | dereference | array_lookup | ... ;
rvalue ::= function_call | constant | ... ;

This divides up all expressions into two disjoint sets:

But there’s an alternative definition. Eli Bendersky redefines lvalue as a “locator value”, and says

An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address).

rvalues are defined by exclusion, by saying that every expression is either an lvalue or an rvalue. Therefore, from the above definition of lvalue, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.

This definition is nicer, because it accounts for another place where we refer to lvalues and rvalues: referencing and dereferencing. This program generates an error:

int foo() { return 4; }
int main(void) {
  int* f = &foo();
  return 0;
}

Clang now decides to use the rvalue terminology!:

% clang lvalue.c
lvalue.c:3:12: error: cannot take the address of an rvalue of type 'int'
  int* f = &foo();
           ^~~~~~
1 error generated.

Because rvalues are ones which do “not represent an object occupying some identifiable location in memory”, we cannot use the & (addressof) operator on them.

But wait … what about this program?

int main(void) {
  void* f = &"some string";
  return 0;
}

It turns out this one is just fine, because … string literals are lvalues! When we write "foo", we reserve memory for that string in an addressable location.


I wrote this because I felt like it. This post is my own, and not associated with my employer.

Jim. Public speaking. Friends. Vidrio.