tags:

views:

221

answers:

5

In C++ whats the difference between char const *ptr=&ch; and const char *ptr=&ch;

+6  A: 

No difference in C++.

It is important const is before * or after *.

Alexey Malistov
+26  A: 

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.

Paul R
+1. Complete answer.
ereOn
+5  A: 

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.

abababa22
+1  A: 

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.

Greg Howell
If anyone's interested, the book 'C++ Gotchas' by Stephen C. Dewhurst talks about this technique of declaring pointers.
TheJuice
A: 

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.

Dave18