|
</a>What's the difference between const int* and int* const ? |
When dealing with pointers const may mean two different things: If we declare a type with const as its first word, we create a "pointer to a const int". This means we have a non-const pointer, and it takes addresses of const int . So for example:
int x = 5; const int* ptr = &x; *ptr = 7; // error
In this example, *ptr is of type const int and therefore the last line raises an error, as the value of a const int cannot be changed. The other case, is when const is not the first word in the type definition. In this case, the const affects whatever is on its left. So the type int* const is a "const pointer to an int". This means such a pointer must be initialized and its value (the address it stores) cannot be changed. However, when dereferencing (i.e. reading) this pointer, we get an int which can be freely changed:
int* const cptr = &x; // must be initialized *ptr = 7; // o.k.
We can also combine both versions and get a "const pointer to a const int":
const int* const cptr = &x; // must be initialized *ptr = 7; // error</ul>
|
|