Why are string literals l-value while all other literals are r-value?

Alok Save picture Alok Save · Apr 4, 2012 · Viewed 7.3k times · Source

C++03 5.1 Primary expressions §2 says:

A literal is a primary expression. Its type depends on its form (2.13). A string literal is an lvalue; all other literals are rvalues.

Similarly, C99 6.5.1 §4 says:

A string literal is a primary expression. It is an lvalue with type as detailed in 6.4.5.

What is the rationale behind this?

As I understand, string literals are objects, while all other literals are not. And an l-value always refers to an object.

But the question then is why are string literals objects while all other literals are not? This rationale seems to me more like an egg or chicken problem.

I understand the answer to this may be related to hardware architecture rather than C/C++ as programming languages, nevertheless I would like to hear the same.

Answer

A string literal is a literal with array type, and in C there is no way for an array type to exist in an expression except as an lvalue. String literals could have been specified to have pointer type (rather than array type that usually decays to a pointer) pointing to the string "contents", but this would make them rather less useful; in particular, the sizeof operator could not be applied to them.

Note that C99 introduced compound literals, which are also lvalues, so having a literal be an lvalue is no longer a special exception; it's closer to being the norm.