const a*, a* const, and const a* const, oh my!

Home/Programming Techniques/const a*, a* const, and const a* const, oh my!

const a*, a* const, and const a* const, oh my!

Everyone knows how to pass a pointer to a function:

void MyFunction(int*){}

int* a = new a;

But how do you make this const correct? (I learned this from here:

Lets start with the non-pointer const syntax:

void MyFunction(const int a){}

This means ‘a’ is passed by value, so if you change a in the function, the object that was passed to the function is not changed in the caller.

Using identical syntax for pointers:

void PointerToConst(const int* a)

means that you can change the address of the pointer, but not the value that it is pointing to. That is,
a = new int;
is valid, and will change the address in the calling function as well. However, *a = 3, is not valid.

Next, let’s move const to the other side:

void ConstPointer(int* const a)

This means that you can change the value that is pointed to, but not the address:
a = new int; is not valid, but *a = 3; is valid.

Finally, we can use both types of const:
void ConstPointerToConst(const int* const a)

which does not allow the address nor the value to change. This is a truly read only object, with the same guarantee that passing a non-pointer object by value gives you – that nothing will have changed in the calling function.

About the Author:

Leave A Comment