Pointer Const-correctness in C++

This short tutorial aims to explain the const correctness of pointers in the C++ language, an often confused concept.

The usefulness of const is the subject of much debate among programmers. Used correctly the const keyword is a powerful tool not only for protecting values from change, but a valuable asset at compile time to draw your attention to the fact that you've tried to change something defined constant (often not what you really intended!).

Const correctness in pointers is important to ensure you are protecting the correct memory. Not only should you consider whether the pointed value should be constant, but perhaps the pointer to that value itself!

Here is a basic example of a pointer setup

int A = 100;
int* pA = &A;
*pA = 200;
 
This is legal code, we are creating an integer (A) and using a pointer to modify its value. Let us consider a different situation surrounding the pointer (pA)

int A = 100;
const int* pA = &A;
*pA = 200;

This is illegal code. Notice that we have now defined our pointer as a "pointer to constant int" (it helps slightly to read the declaration backards). When we try to change the value with this pointer, we are unable to do so:

'pA' : you cannot assign to a variable that is const

Now we will move the const keyword. Look at the following:
int A = 100;
int* const pA = &A;
*pA = 200;

This is now legal code once again, but why? By moving the const keyword to the right of the type, we are declaring that the pointer itself is the constant value rather than the value to which it points. We can prove this by attempting to change the pointer to point to another integer, for example; B

int A = 100;
int B = 200;
int* const pA = &A;
pA = &B;

Here, the same error is generated as previously. We are unable to modify the pointer to point to a different area of memory.

If we wished, we could create a pointer which is both constant and pointing to a constant memory location (essentially a read-only location)

int A = 100;
int B = 200;
const int* const pA = &A;
pA = &B;
*pA = B;

Notice that neither of these assignments are valid given the totally const nature of the pointer.

The const_cast operator

This tutorial would not be complete without touching on the const_cast operator. I personally do not condone the use of this operator since it essentially provides a naughty hack to pointers, giving them no real purpose in my opinion. However, there are occasions where such a 'hack' is useful and acceptable. Study the following example:

int A = 100;
int B = 200;
const int* pA = &A;
int* pA2 = const_cast <int*> (pA);
*pA2 = 50;

Declaring pA2 using a const_cast explicitly removes the constness from pA, allowing the value to be therefore modified from the new pointer. Exercise some caution using this operator, being careful not to modify values which genuinely should not be modified.

This concludes the tutorial.




Back to Tutorials