Constant Pointers & Pointers to Constants

The use of the keyword const when working with pointers is the same as when it's used at any other time: you don't want the value to change! It is that simple. It was named const for a reason.

 

We (should) already know that a pointer is assigned the address of the target using the & address of operator:

 

int myInt = 42 ;

int *myPtr = &myInt ;

 

So, by making specific expressions const in the statement, we are stating that we do not want these values to change.

 

Here's three examples:

 

The first declares a constant int pointer. Thus stating that the value being pointed at cannot be changed:

const int *myPtr = &myInt ;

 

The second declares a constant pointer to an int. Thus the location stored on the pointer cannot change the address of what is being pointed at:

int * const myPtr = &myInt ;

 

Finally, this example declares a pointer to an int where both the value being pointed to and its address cannot change:

const int * const myPtr = &myInt ;

 

 

Basically, the placement of the keyword const determines what is being declared as a constant, the value, the address or both!

 


 

Const correctness, makes it clear that you do not want an object to change.

 

Good idea to create reference parameters const:

 

return_datatype funcName(const myClass& objectA){

...code body...

}

Leave a Reply