Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's the difference between:

char * const  

and

const char * 
like image 752
LB. Avatar asked May 20 '09 22:05

LB.


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

The main difference between them is that the first is an array and the other one is a pointer. The array owns its contents, which happen to be a copy of "Test" , while the pointer simply refers to the contents of the string (which in this case is immutable).

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 a const char pointer?

const char* is a pointer to a constant char, meaning the char in question can't be modified. char* const is a constant pointer to a char, meaning the char can be modified, but the pointer can not (e.g. you can't make it point somewhere else).


1 Answers

The difference is that const char * is a pointer to a const char, while char * const is a constant pointer to a char.

The first, the value being pointed to can't be changed but the pointer can be. The second, the value being pointed at can change but the pointer can't (similar to a reference).

There is also a

const char * const 

which is a constant pointer to a constant char (so nothing about it can be changed).

Note:

The following two forms are equivalent:

const char * 

and

char const * 

The exact reason for this is described in the C++ standard, but it's important to note and avoid the confusion. I know several coding standards that prefer:

char const 

over

const char 

(with or without pointer) so that the placement of the const element is the same as with a pointer const.

like image 101
workmad3 Avatar answered Sep 25 '22 03:09

workmad3