Pointers and the const keyword

One thing I remember from my early days as a C-programmer as all too easy to mess up is the usage of the const keyword in the context of pointers.

Given the following lines of code, which pointer is a pointer to a constant value, and which is a constant pointer to a value?


int v1, v2;
const int * p1 = &v1;
int * const p2 = &v2;

The simple rule of thumb to decipher this type of declaration, I soon learned, was to read the declaration from the very end.

So, p1 is a pointer to an int that is constant, and p2 is a constant pointer to an int.

Thus, neither of the two expressions would be allowed:


*p1 = 2;
p2 = &v1;

But both these would:


p1 = &v2;
*p2 = 1;

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *