const char* and char const* - are they the same?

Luchian Grigore picture Luchian Grigore · Nov 11, 2011 · Viewed 35.6k times · Source

From my understanding, const modifiers should be read from right to left. From that, I get that:

const char*

is a pointer whose char elements can't be modified, but the pointer itself can, and

char const*

is a constant pointer to mutable chars.

But I get the following errors for the following code:

const char* x = new char[20];
x = new char[30];   //this works, as expected
x[0] = 'a';         //gives an error as expected

char const* y = new char[20];
y = new char[20];   //this works, although the pointer should be const (right?)
y[0] = 'a';         //this doesn't although I expect it to work

So... which one is it? Is my understanding or my compiler(VS 2005) wrong?

Answer

Greyson picture Greyson · Nov 11, 2011

Actually, according to the standard, const modifies the element directly to its left. The use of const at the beginning of a declaration is just a convenient mental shortcut. So the following two statements are equivalent:

char const * pointerToConstantContent1;
const char * pointerToConstantContent2;

In order to ensure the pointer itself is not modified, const should be placed after the asterisk:

char * const constantPointerToMutableContent;

To protect both the pointer and the content to which it points, use two consts.

char const * const constantPointerToConstantContent;

I've personally adopted always putting the const after the portion I intend not to modify such that I maintain consistency even when the pointer is the part I wish to keep constant.