Home > Net >  What is a legal definition of a pointer to a pointer to a const object?
What is a legal definition of a pointer to a pointer to a const object?

Time:10-22

I know from this answer that a pointer const int** z is supposed to be read as

Variable z is [a pointer to [a pointer to a const int object]].

In my humble opinion, this would mean if z=&y then y should be a pointer to a const int object. However, the following code also compiles:

int x=0;
int const* y=&x;
const int** z=&y;

Why is an int const* object i.e. a const pointer to an int instead of a pointer to a const int acceptable to be the pointed object of z?

CodePudding user response:

Why is an int const* object i.e. a const pointer to an int

No.

int const * and const int * are the same type.

People sometimes prefer writing int const * because it reads right-to-left as "pointer to a const int", whereas const int * really reads as "pointer to an int (which is const)".

A const pointer to an int is int * const.

Try it:

  int a = 42;
  const int * y = &a;
  int const * z = &a;

  *y = 24; // compile error assigning to const
  *z = 24; // compile error assigning to const

  int b = 0;
  y = &b;
  z = &b; // re-pointing non-const pointers is fine
  *z = 1; // still a compile error

  int * const x = &a;
  *x = 24; // fine, assigning via pointer to non-const
  x = &b;  // error reassigning a const pointer

CodePudding user response:

You are misunderstanding what the const refers to. A const always refers to the element to the left of it - unless it is the leftmost element itself, in which it refers to the element to the right.

This means that int const * is a pointer to a const int, not a const pointer to int as you think. To get that, you would have to write int * const

int const * and const int * are two ways of writing exactly the same: a pointer to a const int.

You get it right if you read declarations from right to left. If const is the leftmost element, add a "that is" before it when reading. Ex:

  1. const int *: pointer to int that is const.
  2. int const *: pointer to const int.
  3. int * const: const pointer to int.
  4. const int * const: const pointer to int that is const.
  5. int const * const: const pointer to const int.

Note that 1/2 are the same, and 4/5 are the same. 1 and 4 are called "west const" since const is on the west/left side, while 2 and 5 are called "east const".

  • Related