How to use Const

Keyword const is an important concept in both C/C++. Because the introduction of objects and objective oriented programming, the usage of const becomes more complicated and more common. The basic idea of introducing const is to remind programmers that something is a constant and should not be changed. Therefore, const is a useful tool to make codes, especially codes maintained by multiple parties, robust.

There are generally two scenarios where const is used: decorating a variable and decorating a function.

Apply const to a variable

When const is applied to a variable (value or pointer), the content of the variable is not changed. This means: * if the variable is a value, once the variable is created, its value cannot be changed. * if the variable is a pointer, the pointed address cannot be changed, but the value pointed by the pointer is still modifiable.

The interpretation order starts from right to left.

// value
const int q = 5;    // const decorates "int q", so q is a constant
q = 4; // invalid

// pointer
int const* p = &q;  // const decorates "* p", so the pointer address is a constant
p = &q + 1;         // invalid
*p = 5;             // valid, because we change the value at the pointed address, the address remains unchanged.

// hybrid
int const* p;       // const decorates "*p" that is a value, so it's a pointer to const int
int *const p;       // const decorates "p" that is a pointer, so it's a const pointer to int
int const* const p; // a const pointer (right const) to a const int (left const)
int ** const p;     // a 2-d const pointer, but the values in the 2-d structure can be modified
int * const * p;    // a pointer to a const pointer then to a int
int const ** p;     // a 2-d pointer to a const int
int *const *const p;// a 2-d const pointer p to a const pointer then to a modifiable int

Apply const to a function

You will generally see three positions to apply const to a function: apply to the return value, apply to the input parameters, and apply at the end of a member function.

// case 1: apply to the return value
const int foo11(int a);     // case 1-1
int *const foo12(int a);    // case 1-2

//case 2: apply to parameters
int foo21(int const a);     // case 2-1
int foo22(int * const p);   // case 2-2
int foo23(const int &r);    // case 2-3

//case 3: apply at the end of a member function
// ... some class defination related codes
int foo3(int a) const;      // case 3