Interview Question
Country: United States
Const int *i and int const *i are same and represent constant value. You cannot change the value of the pointer
Int *const i represent consant pointer. You cannot change the pointer to which it. Is pointeting to,, you can change the value
The best way to understand this is ..
1. whatever comes to right of "const" .. become a constant.
2. so for eg. const int *i .. here *i ( deferenced value) is constant so you cannot change the VALUE the pointer points to..
..another eg. int *const i .. here i comes after the const keyword.. hence only the address that the pointer points to stays constant..i.e u can change the value pointed to by the pointer. .but you cannot make it point to any other mem loc.
In C you declare the type of an expression, not a variable.
const int *i; -> *i is an int, that cannot be modified
int const *i; -> same as before, no difference
int *const i; -> i is an int* and the pointer itself cannot be modified - but the content can! e.g. *i = 10; is absolutely valid
const int * const i; -> neither of the pointer, nor the content can be modified. [This only makes sense with initializing i to an existing address]
The way to understand pointer and const declarations is to read them right-to-left.
Pointer (*) to constant (const) int. It means you can reassign the pointer, e.g. i = &some_other_constant_int is valid, but you cannot alter the int through the pointer, because the int is constant, e.g. *i = 2 is invalid.
Constant (const) pointer (*) to int. This means the pointer itself is constant, but the value it points to is not. So *i = 2 would be valid, but i = &some_other_int would not be.
Pointer(*) to an int constant. This is the same as int const *i. Because of this and because the more natural way to be consistent with the right-to-left rule is to write int const * i, some programmers dislike const int* i. However, I would note that unsigned int * is still the way to declare a pointer to unsigned int, so to me it makes good sense to say that const int * is a pointer to const int. I just read "const int" as one term, just like I would consider "unsigned int" to be one term.
Now that we know this, how about a new one?
Easy, using the right-to-left rule. Constant (const) pointer (*) to constant (const) int. In other words, neither the pointer nor the value it points to can be modified. *i = 2 is invalid, and so is i = &some_other_const_int. Based on the previous discussion, you might correctly infer that "const int * const i" would mean the same thing.
- eugene.yarovoi September 22, 2012