Because literals are constant. 1 cannot become 2, and "abd"
cannot become "edf"
.
If C++ allowed you to take literals by non-const
reference, then it would either:
- Have to allow literals to change their meaning dynamically, allowing you to make 1 become 2.
- Expect the programmer to take extra care to modify values only via those references which do not refer to literals, and invoke undefined behaviour if you get it wrong.
(1) would create chaos in your program, because x == 1
could mean "is x equal to 2" depending on the context, and (2) is impossible to achieve because how is void display(int& a)
supposed to know if it receives a literal reference or not?
Since neither of these two options makes sense, literals can only be passed by const
references.
Actually, the deprecated conversion from string literals to char*
is a good example of why the rules make a lot of sense, although it's not a reference but a pointer. You are allowed to let a char*
point to "abc"
, but an attempt to actually utilise the "modifiability" attribute of the char*
and modify one of the char
elements results in undefined behaviour. This makes the whole deprecated conversion both dangerous and useless (in non-legacy code).
You wouldn't want to have such troubles in all other parts of the language, would you?