开发者

Declaration of pointers in C++

开发者 https://www.devze.com 2022-12-29 04:58 出处:网络
In C++ 开发者_开发问答whats the difference between char const *ptr=&ch; and const char *ptr=&ch;They are the same, i.e. pointer to const char.

In C++ 开发者_开发问答whats the difference between char const *ptr=&ch; and const char *ptr=&ch;


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.


No difference in C++.

It is important const is before * or after *.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消