C++ – Understanding ‘int const *p’ vs ‘const int *p’

c++constants

#include <iostream>
using namespace std;

int main(int argc, char* argv[])
{
    int i1 = 0;
    int i2 = 10;

    const int *p = &i1;
    int const *p2 = &i1;
    const int const *p3 = &i1;

    p = &i2;
    p2 = &i2;
    p3 = &i2;

    cout << *p << endl
        << *p2 <<endl
        << *p3 <<endl;
    return 0;
}

The code can be compiled with both VC6.0 and VC2010.
But I have questions as blow:

const int *p = &i1;

It means what the "p" points can not be modified,but p can not be modified,am I right?
so

p = &i2;

this line can be complied,yes?

This line:

int const *p2 = &i1;

In my mind,this means p2 can not be modified while what p2 points can be changed, am i right?
Why the

p2 = &i2;

can be compiled?

About this line:

const int const *p3 = &i1;

p3 = &i2;

Oh,god… I am crazy. I have no idea why this line can be compiled with no error…
Can any body help me?

Another code which confused me is here:

class Coo2    
{      
 public:     

 Coo2() : p(new int(0)) {}    

 ~Coo2() {delete p;}    


    int const * getP() const   
    {      
         *p = 1;         
         return this->p;      
    }      

 private:    
      int* p;    
};   

why this code can be compiled?
In

int const * getP() const

I have change the value or *p !

Best Answer

Here we consider 4 types of pointers declarations:

  1. int * w; It means that w is a pointer to an integer type value. We can modify both the pointer and its content. If we initialize w while declaration as below: int * w = &a;
    Then, both of below operations are viable:
    w = &b;(true)
    *w = 1;(true)

  2. int * const x;
    It means x is a constant pointer that points to an integer type value. If we initialize x while declaration as below:
    int * const x = &a;
    Then, we cannot do: x = &b;(wrong) because x is a constant pointer and cannot be modified.
    However, it is possible to do: *x = 1;(true), because the content of x is not constant.

  3. int const * y; //both mean the same
    const int * y;
    It means that y is a pointer that points to a constant integer value. If we initialize y while declaration as below:
    int const * y = &a;
    Then, it is possible to do: y=&b;(true) because y is a non-constant pointer that can point to anywhere.
    However, we cannot do: *y=1;(wrong) because the variable that y points to is a constant variable and cannot be modified.

  4. int const * const z; //both mean the same
    const int * const z;
    It means that z is a constant pointer that points to a constant integer value. If we initialize z while declaration as below:
    int const * const z = &a;
    Therefore, non of below operations are viable:
    z = &b;(wrong)
    *z = 1;(wrong)

Related Question