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
.
Now that you know the difference between char * const a
and const char * a
. Many times we get confused if its a constant pointer or pointer to a constant variable.
How to read it? Follow the below simple step to identify between upper two.
Lets see how to read below declaration
char * const a;
read from Right to Left
Now start with a
,
1 . adjacent to a
there is const
.
char * (const a)
;
---> So a
is a constant
(????)
.
2 . Now go along you get *
char (* (const a))
;
---> So a
is a constant
pointer
to (????)
.
3 . Go along and there is char
(char (* (const a)))
;
---> a
is a constant
pointer
to character
variable
a is constant pointer to character variable.
Isn't it easy to read?
Similarily for second declaration
const char * a;
Now again start with a
,
1 . Adjacent to a
there is *
---> So a
is a pointer
to (????)
2 . Now there is char
---> so a
is pointer
character
,
Well that doesn't make any sense!!! So shuffle pointer
and character
---> so a
is character
pointer
to (?????)
3 . Now you have constant
---> so a
is character
pointer
to constant
variable
But though you can make out what declaration means, lets make it sound more sensible.
a is pointer to constant character variable