dharag
dharag

Reputation: 299

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

Upvotes: 6

Views: 1175

Answers (2)

Pete Becker
Pete Becker

Reputation: 76245

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!";

Upvotes: 8

Vaughn Cato
Vaughn Cato

Reputation: 64308

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.

Upvotes: 6

Related Questions