Tuesday, July 1, 2008

C++ quick tutorial: const

The const keyword allows you to specify whether a particular variable can be modified or not.

The simplest usage of const is this, for example:

const int i = 8;

This just means that the variable i is always 8 and cannot be changed. An alternative way of writing this is:

int const i = 8;

which means that same thing. The value of the variable i cannot be changed. Clearly you must initialize constant variables when they are declared, as you can't change their value later! Using const in this context is an alternative to using #define, for example:

#define i 8

What about this example?

const int *px;

This basically means that *px is a const int, i.e. px is a pointer to a constant integer. The important thing to remember is that while *px can be pointed to any integer, you cannot change the value of the integer.

Here's another example:

int x;
int * const px = &x;

The difference here is that the const is after the *. The value x can be changed, however the address pointed to by px can't be changed.

Here's yet another example:

int x = 0;
const int * const px = &x;

In this case, we cannot change the value of x using the pointer px, and we cannot point px to another address.

Another usage is in passing parameters to functions. For example, firstly consider:

void myfunction(mystructure in);

Assume mystructure uses a large amount of memory. When myfunction is used, a copy of the structure is made which is available only inside the function. This may take a long time, and/or may use too much memory. Instead, we could pass the structure in by reference:

void myfunction(mystructure &in);

which means that inside the function we don't just have a copy of the mystructure variable, we have variable itself. This of course means that it is possible to modify this variable. If we want to ensure that it cannot be modified, we would make use of const:

void myfunction(mystructure const &in);

No comments: