I understand that
char *s = "Hello World!" ;
is stored in read only memory and the string literal cannot be modified via the pointer.
How is this different from
const char *s = "Hello World!";
Also is the type of 'string' char * or const char * ?
The difference is that the latter is legal and the former is not. That's a change that was made in C++11. Formally, "Hello World!"
has type const char[13]
; it can be converted to const char*
. In the olden days, its type could be char[13]
, which could be converted to char*
. C++ changed the type of the array by adding the const
, but kept the conversion to char*
so that existing C code that used char*
would work in C++, but modifying the text that the pointer pointed to produced undefined behavior. C++11 removed the conversion to char*
, so now you can only legally do
const char *s = "Hello world!";
By giving the type as const char *
, it makes it harder to accidentally overwrite the memory, since the compiler will give an error if you try:
const char *s = "Hello World!";
s[0] = 'X'; // compile error
If you don't use const
, then the problem may not be caught until runtime, or it may just cause your program to be subtly wrong.
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