constant pointer vs pointer on a constant value [duplicate] constant pointer vs pointer on a constant value [duplicate] c c

constant pointer vs pointer on a constant value [duplicate]


char * const a;

means that the pointer is constant and immutable but the pointed data is not.
You could use const_cast(in C++) or c-style cast to cast away the constness in this case as data itself is not constant.

const char * a;

means that the pointed data cannot be written to using the pointer a.Using a const_cast(C++) or c-style cast to cast away the constness in this case causes Undefined Behavior.


To parse complicated types, you start at the variable, go left, and spiral outwards. If there aren't any arrays or functions to worry about (because these sit to the right of the variable name) this becomes a case of reading from right-to-left.

So with char *const a; you have a, which is a const pointer (*) to a char. In other words you can change the char which a is pointing at, but you can't make a point at anything different.

Conversely with const char* b; you have b, which is a pointer (*) to a char which is const. You can make b point at any char you like, but you cannot change the value of that char using *b = ...;.

You can also of course have both flavours of const-ness at one time: const char *const c;.


char * const a;

*a is writable, but a is not; in other words, you can modify the value pointed to by a, but you cannot modify a itself. a is a constant pointer to char.

const char * a; 

a is writable, but *a is not; in other words, you can modify a (pointing it to a new location), but you cannot modify the value pointed to by a.

Note that this is identical to

char const * a;

In this case, a is a pointer to a const char.