constant pointer to an address or pointer to a value

守給你的承諾、 提交于 2019-12-13 20:38:28

问题


Do int const *a and const int *a mean that "a is a integer pointer to a constant value" and "a is a pointer to a constant address", respectively , or is it viceversa?

This was asked to me in an interview. After reading a lot about the same I am still very much confused regarding it.


回答1:


  • const int *a - a is writable (can point to a different thing), *a is not writable (cannot write to pointed-to thing)
  • int const *a - same as above
  • int * const a - a is not writeable (cannot point to a different thing), *a is writable (can write to pointed-to thing)
  • const int * const a - neither a nor *a are writable
  • int const * const a - same as above

If you read the first two cases as

const int (*a)
int const (*a)

it's clear that the const is modifying the int type specifier; we're pointing to a constant integer.

If you read the third case as

int (* const a)

then the const is modifying the pointer declarator *a; we have a constant pointer to an integer.

Then you read the final two cases as

(const int) (* const a)
(int const) (* const a)

then it's clear that we have one const modifying the type specifier and the other modifying the pointer, so we have a constant pointer to a constant integer.




回答2:


int const *a;

which is equivalent to:

const int *a;

means a is a pointer to a const int object.




回答3:


When the const hops over the type keyword (int), the meaning doesn't change.

The meaning changes when the const hops over the *.

const int *a; /* The int is const */
int const *b; /* The int is const */
int *const c; /* The pointer is const */


来源:https://stackoverflow.com/questions/22332677/constant-pointer-to-an-address-or-pointer-to-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!