问题
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-ais writable (can point to a different thing),*ais not writable (cannot write to pointed-to thing)int const *a- same as aboveint * const a-ais not writeable (cannot point to a different thing),*ais writable (can write to pointed-to thing)const int * const a- neitheranor*aare writableint 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