Showing posts with label const. Show all posts
Showing posts with label const. Show all posts

Sunday, March 4, 2012

#6 March 4

Another week and some more intricacies of C++ come to light - the many different uses of the const keyword. While I have covered const pointers before, it's still handy to brush up on how const can change the usage of a variable or a pointer depending on how you place it in the declaration.

So let's break things down:
When you declare something as const, quite intuitively, you're saying that it can't be changed. This obviously means that a const variable MUST be initialized during declaration.
So, for example:

const i = 2;

would initialize the constant in i to 2 and then you would not be able to modify it (i becomes read-only).

This becomes slightly more tricky once you start using pointers:

const int* p = &i;
int* const p = &i;

In the first case, we're declaring a pointer to a constant, i.e., the value being pointed to by p (in this case i) must be constant and cannot be changed, while p itself can. Thus I can reassign p, but something like ++*p would not be allowed.

In the second case, we're declaring a constant pointer. This means once initialized to some address, we will not be able to modify p. This is particularly useful if you think of pointers being returned to indicate the start of an allocated memory location - we want to ensure that we keep this address constant.

There are other variants to this, including mixing it up with references, but once these 2 have been clearly distinguished, the rest fall into place.