const keyword in CPP
- June 12, 2012
- Posted by: Kamal Rawat
- Category: C++
What is the difference between the below two definition of pointers a and b:
int x = 5; int* const a = &x;
int x = 5; const int * b = &x;
In the first statement
int * const a = &x;
a is a const pointer to integer. It means that a itself is a constant pointer and cannot be changed, but the value pointed to by it can be changed.
*a = 10; // OK a = &y; // ERROR
In the Second definition
const int * b = &x;
b is pointing to a constant integer, but b itself is not a constant. So you may change b but not the value pointed to by b.
*b = 10; // ERROR b = &y; // OK
The best way is to read such definitions is to read them in the backward direction (from the variable being defined). So const int * b means that b is a pointer to int which is const. and int * const a means that a is a constant pointer to int.
By the way, the below definition
const int * const c = &x;
means that c is a constant pointer and is pointing to a constant integer. Hence neither c and value-at c can be changes
Note that, x may not be a constant but if a constant pointer is storing its address then the pointer will treat as if it is pointing to a constant integer memory. Its value can be changed by directly assigning value to x but it cannot be changed via pointer.