Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char * and char *

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 * ?

like image 254
dharag Avatar asked Mar 29 '13 13:03

dharag


2 Answers

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!";
like image 139
Pete Becker Avatar answered Nov 06 '22 04:11

Pete Becker


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.

like image 29
Vaughn Cato Avatar answered Nov 06 '22 05:11

Vaughn Cato