Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 397
Luchian Grigore Avatar asked Nov 11 '11 09:11

Luchian Grigore


People also ask

What is const char * const *?

const char* const says that the pointer can point to a constant char and value of int pointed by this pointer cannot be changed. And we cannot change the value of pointer as well it is now constant and it cannot point to another constant char.

What is the difference between char * p and char * p?

char* p and char *p are exactly equivalent. In many ways, you ought to write char *p since, really, p is a pointer to char . But as the years have ticked by, most folk regard char* as the type for p , so char* p is possibly more common.

What is the difference between constant pointer and pointer constant?

In the constant pointers to constants, the data pointed to by the pointer is constant and cannot be changed. The pointer itself is constant and cannot change and point somewhere else.

What is the difference between int * const C and const int * C?

const int * And int const * are the same. const int * const And int const * const are the same. If you ever face confusion in reading such symbols, remember the Spiral rule: Start from the name of the variable and move clockwise to the next pointer or type. Repeat until expression ends.


1 Answers

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.

like image 98
Greyson Avatar answered Sep 21 '22 08:09

Greyson