Search code examples
c++pointersconstantsauto

Is "pointer to const int" same as " const int* "


I am reading about pointers and got confused in one part. The code given is as follows:

int i=0;
const int ci = i;
auto *p = &ci;`

Now the question is what will be the type of p? I am thinking that p will be a pointer to const int. Is this correct? And if yes will this be equal to const int*? Is a pointer to const int the same as const int*?


Solution

  • In C++, the const keyword generally applies to the part of the type to its left.

    So int const* is a pointer to a constant integer, and int*const is a constant pointer to a non-constant integer.

    The type of p in your example is a int const*.

    The habit of putting const to the right is known as east const.

    Now there is an exception to the "const applies to the left"; when there is nothing to the left, it applies to the right instead. This confusing exception means that const int* is int const*. But using X=int*; const X becomes int*const.

    The habit of putting const on the left, and the resulting confusion, is known as west const.

    In short, the answer is yes, unless you add aliases.