Const in Pointer

Const in Pointer

Two types of const there are in pointer

In C when we create a pointer, we can use const at two different places, one to make pointer constant so that it doesn't point to any other memory location and one to make the value in a memory location constant so that, in code we cannot change value at that address. Lets see what is the difference...

I hope after this it will be clear, where to use which const in a pointer

When we use const before the whole definition which is like:

const char *a;

OR

const int *b;

Then value of variable pointed by a or b cannot change but we can change the pointer itself i.e. we can change to which memory location our pointer will point to.

When we use const after star(*), like:

char *const a;

OR

int *const b;

then we can change the value at memory pointed by a or b but we can't change the address to which a or b variable to point to any other address.

We can combine both of these implementation to make our variable completely constant I like to say which means neither we can change the value at memory address, nor we can modify to which location does the pointer point to. We can declare it as:

const char *const a;

OR

const int *const b;

By using these techniques we can make pointers and values constants to maybe store secret keys or prevent error that can happen on modifying a pointer or its value and in all make a cleaner and efficient code.