Literals are, in general, prvalue
s.
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
?
String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string."
Definition. String literal in Java is a set of characters that is created by enclosing them inside a pair of double quotes. In contrast, String Object is a Java is a set of characters that is created using the new() operator. Thus, this explains the main difference between string literal and string object.
Constants refer to fixed values that the program may not alter during its execution. These fixed values are also called literals. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are enumeration constants as well.
A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With