Thursday, August 6, 2009

const pointer and pointer to a const

Here is a good question; What's the different between:
a) const char* c;
b) char* const c;

A pointer is itself a variable which holds a memory address of another variable - it can be used as a "handle" to the variable whose address it holds.

a) This is a changeable handle/pointer to a const variable.
b) This is a const handle/pointer to a changeable variable.

This example might explain better:

int main()
int for_a = 100;
int for_b = 200;
int for_test = 300;

const int* a = &for_a;
int* const b = &for_b;

a++; // allowed
// *a = for_test; // not allowed: "assignment of read-only location"

// b++; // not allowed: "increment of read-only variable"
*b = for_test; // allowed

printf("Value of *a = %d, value of *b = %d \n", *a, *b);

return 1;

Irrelevant, but then 'const char* const c;' would mean a non-changeable pointer to a non-changeable variable.

No comments: