Reference to a literal is possible only if the reference is declared as constant.
But why is a pointer to a const object not possible in case of literals?
i.e.
int const& ref = 5;//
But why is the same feature not available for a pointer, pointing to a constant object?
5
In the C++ view of the world, a literal does not occupy any memory. A literal just exists.
This view makes that there is no address for a pointer to refer to when it would point to a literal and for that reason, pointers to literals are forbidden.
Const references are actually the exception here in that they allow apparent indirect access to a literal. What happens underneath is that the compiler creates a temporary object for the reference to refer to and that temporary object is initialized with the value of the reference.
This creating of a temporary that the reference gets bound to is only allowed for const references (and gets used in other scenarios as well, not only for literals), because that is the only case where a reference/pointer to a temporary won’t have undesired side-effects.
2
In C++, literals exist only in the compiler. They are used in expressions, assignments and initialisations. The value of a literal may be found in the running program if it has been used to initialise a variable or temporary, but the literal itself is not.
A name that is a reference to a literal has meaning, because a reference is a value, so that wherever the name is used it can be replaced by the literal value itself. In certain special cases it is replaced by a temporary variable initialised to that value, and the required const qualifier protects that variable against being modified.
A name that is a pointer to a literal has no meaning. Pointers refer to storage locations, and a literal doesn’t have one.
It would be hypothetically possible for C++ to allow pointers to literals, and to interpret them as pointing to a temporary variable initialised to that value, and presumably to protect that value with a const qualifier. The reasons it wasn’t defined that way is either (a) it’s not very useful (b) it would be incompatible with C. You’d have to ask Bjarne about that one.
Please note that the above applies to integers and floats. Literal strings have different rules, because in many ways they are already const pointers.
1
In my opinion, this behavior comes from the semantical differences of pointers and references in C++.
The following code snippet with reference works fine:
const int& r = 5;
std::cout << &r << std::endl;
… since a temporary object is created when you assign the value to the const reference, and you can take the address of that temporary object.
The equivalent code snippet with pointer would be like this:
const int *p = &5;
std::cout << p << std::endl;
This one, however, does not compile, since &5
, i.e. address of 5, has no meaning in C.