In C++ whats the difference between
char const *ptr=&ch;
and
const char *ptr=&ch;
views:
221answers:
5No difference in C++.
It is important const
is before *
or after *
.
They are the same, i.e. pointer to const char
.
However char * const ptr
is different, being a const pointer to (non-const) char
.
And just to complete the set, const char * const ptr
is a const pointer to const char
.
Const applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right). So there is no difference.
char * const ptr
would be a const pointer to variable value though.
Other answers have covered the technical solution - your two examples are the same.
Many people prefer to read from right to left when dealing with const
in C++. In English, we like to think of a constant X, while C++ likes to parse an X const. Reading right to left yields a more English result.
A rather extreme example:
C const * bar(A * const, B const * const) const;
From right to left this reads as 'A constant function bar
taking as parameters a constant pointer to an A
and a constant pointer to a constant B
, returning a pointer to a constant C
'. Note that all three kinds of pointers are different.
char const *ptr=&ch;
and const char *ptr=&ch;
means char is const, where as the pointer is variable (or it can be changed).
But In case of char * const ptr
, you cannot re-assign the pointer once you set it. so its a const pointer to a char string.