Constant Pointer And Pointer To A Constant

October 6, 2008

The keyword const specifies that you can not change the value of the variable. When it comes to pointers, we can have two types of constants.

Constant Pointer

It prevents you from changing the pointer from one memory location to another. However, you can change the contents of the pointer.

   int myInt = 10;
   int* const pInt = &myInt;  // Constant pointer
   int myNewInt = 20;
   pInt = &myNewInt; //Illegal 
   *pInt = 30; // Legal

Pointer to a constant

It prevents you from changing the contents of the memory location. However, you can reassign the pointer to a new memory location.

   int myInt = 10;
   const int* pInt = &myInt;  // Pointer to a constant
   int myNewInt = 20;
   pInt = &myNewInt; //Legal 
   *pInt = 30; // Illegal