char* const p = "world";
This is illegal in the current C ++ standard (C ++ 11). Most compilers still accept it because they use the previous C ++ standard (C ++ 03) by default, but even there the code is outdated, and a good compiler with the correct warning level should warn about this.
The reason is that the literal type "world"
is equal to char const[6]
. In other words, the literal is always constant and cannot be changed. When you speak...
char* const p = "world";
... then the compiler will convert the literal to a pointer. This is done implicitly by an operation called "array decay": the C array can be implicitly converted to a pointer pointing to its beginning.
So, "world"
converted to a value of type char const*
. Pay attention to const
- we are not yet allowed to change the literal, even if it is accessible through a pointer.
Alas, C ++ 03 also allows you to assign literals to a non- const
pointer to provide backward compatibility with C.
Since this is an interview question, the correct answer is this: the code is illegal and the compiler must not allow it. Heres the corrected code:
char const* const p = "world";
We used two const
here: the literal requires the first. The second one is the pointer itself (and not the pointed value) const
.
source share