简体   繁体   中英

constant pointer to an address or pointer to a value

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.

int const *a;

which is equivalent to:

const int *a;

means a is a pointer to a const int object.

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 */
  • 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM