Constant variables

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Constant variables

The keyword const

Using the keyword const, we can enforce that the value of a variable will not change by making any attempt to change it cause an error. This is useful as this may prevent accidental changes to a variable for which the value should stay the same (Ex. A variable storing the value of PI).

Constant variable

We define a constant variable the same as usual, but by adding the keyword const before its type:

const int constVar = 7;

Once it is defined, we cannot change its value, so the following would cause an error:

constVar = 4; // Error.

We can however still use its value:

int var = constVar;

Pointer to a constant variable

Here we define a pointer to a constant variable (const keyword before the asterisk):

const int * ptr;

We make it point to a variable:

ptr = &var;

We can not change the value of the variable it points to:

*ptr = 13; // Error.

But we can use its value:

int var2 = *ptr;

Constant pointer

Here we define a constant pointer (const keyword after the asterisk):

int * const ptr = &var;

We can not change which variable it points to:

ptr = &var2; // Error.

But we can use and change the value of the variable it points to:

*ptr = 77;

Constant pointer to a constant variable

We define a constant pointer to a constant variable:

const int * const ptr = &var;

We can not change which variable it points to, nor its value:

ptr = &var2; // Error. *ptr = 13; // Error.

We can only use the value of the variable it points to:

int var3 = *ptr;