Friday, June 20, 2008

Const Pointers, Pointers to Const, Volatile

Constant Pointers and Pointers to Const

Honestly, the first time I saw these statements, I got a bit confused.
const int * p;
int * const q;
const int * const r;

It is easy actually. The technique is to read from right to left. But note that const type  and type const are the same. So const int and int const are equivalent as well as const Object and Object const.

p is a pointer to a constant integer. This means that the following is valid:
const int xx = 10;
int xy = 11;
p = &xx; //okay
p = &xy; //okay
But p cannot be used to modify the value at the address it dereferences because it is constant.
*p = 120; //error

q is a constant pointer to an integer. This means that once initialized, q can never be set again.
q = &xx; //okay
q = &xy; //error

r is a constant pointer to a constant integer. This is a combination of the two rules above.

Volatile

The volatile keyword is used to denote that the compiler cannot make assumptions on its value and not optimize.

No comments: