Using the const Qualifier with Pointers

A variable declared with the const qualifier is a constant, meaning that it cannot be modified. Any assignment to a constant variable or parameter will result in an error. However, using the const qualifier with a pointer can be confusing because pointers involve two variables: the pointer itself and the value that it points to. Thus, depending upon where the const qualifier is located in the declaration, it can declare the value of the pointer to be constant, or the value it points to.

Typically, the const qualifier comes before the type identifier.

void foo(const int bar)

{

bar = 1; /* Error */

}

When used with a pointer, if the const qualifier is before the asterisk, the value referenced by the pointer is constant. In the following example, the integer that bar points to cannot be modified, but bar can be assigned the address of another integer.

void foo(const int *bar)

{

*bar = 1; /* Error */

}

If the const qualifier is after the asterisk, the pointer itself is constant. In the following example, the integer that bar points to can be modified, but bar cannot be changed to point to a different integer.

void foo(int * const bar)

{

*bar = 1; /* OK */

}

You can also make both the pointer and the variable constant by using the const modifier before and after the asterisk. In this case, both the pointer and the value it references are constants.

void foo(const int * const bar)

{

...

}