Why are literals not const (except strings)?

Viewed 732

Literals are, in general, prvalues. Strings are a special case, defined as an array of char (meaning lvalue). This question is specifically about not string literals.

Why are non-string literals not const?

foo(42); // passes foo an `int`, not a `const int`.

You can't modify a non-string literal, so doesn't it make sense for it to be const?

2 Answers

The literal answer is probably because literals predate the addition of const to the language, so naturally they are not const.

But the practical answer is - const prvalues are fundamentally strange things. You cannot create them from any of the fundamental types, but you can have a const prvalue of class type. But... why? Typically, we make things const to prevent further modifications right. But if it's a prvalue, it's not even a thing with identity - who is going to be there to observe its unintended modification? const prvalues prevent moving - because they're const, so you can't move from them, so its a premature pessimization.

Note that the one thing that could go wrong, that a hypothetical const literal would prevent, is already explicitly forbidden by the language:

void foo(int&);
foo(42); // error

But rather than making 42 const, the language made lvalue references non-const not allowed to bind to rvalues.

Remember that by default C++ is pass by value, meaning values are copied.

There's no way to modify a numeric literal value like 42, because all you have is a copy in a variable. The literal value itself doesn't even have to be stored in memory, the compiler could use it directly in the generated code.

Related