C const

In C const is the keyword to create constants (variables which don’t change their value). Normally the usage of const is straightforward, but it becomes tricky when used with pointers.

We declare constants to show that we have no intention of modifying their value. If we later forget that and try to modify them, the compiler will give us an error or warning.



Creating and using constants

To create a constant in C, put the keyword const before or after the type of the variable:

1
2
const float _pi = 3.14;
int const size = 10;

These both examples are correct declarations. We need to do the initialization immediately. This is done on the same row with the declaration, because we cannot modify the value later. If you miss the initialization you should get a warning (not an error).

Attempting to modify a constant will result in a compile error. For instance, if we try to increase the “size” from the example above, we get an error and the program will not compile;

        size = 15; //This will result in a compile error saying that you cannot modify a constant

How not to use pointers and const in C

We can change the value of a constant through a pointer …but if we do so, chances are that the constant should be a regular variable and doesn’t need to be declared const.
Anyway, when we do modify the constant, the compiler should give us a warning, but still compile and run the code successfully.

1
2
3
4
int const size = 10;
int* ptr_size = &size; //Create a modifiable pointer to a constant - warning
(*ptr_size)++;
printf("%d\n", size); //print 11

Pointer to a constant

In C, to define a pointer to a constant value put the const keyword before the pointer type and asterisk:

1
const float *ptr_to_constant = &_pi;

Now:

  • we cannot change the content of the variable, pointed by our pointer
    *ptr_to_constant = 0; // Error
  • we can change the pointer itself to refer another variable.
    ptr_to_constant = &gravity; // That is OK

Constant pointer to a variable value

In C, to define constant pointer to a variable value put the const keyword after the pointer type and asterisk:

1
int* const constant_ptr = &count;

Now:

  • we cannot assign the pointer to another variable:
    constant_ptr = &count;
  • we can change the value of the pointer variable:
    count = 5;
    (*constant_ptr)++;

Examples download

You can download all examples from the following link: c-const-example.zip or Git Hub

Here is the compilation and the output. You should see a warning like "initialization discards 'const' qualifier from pointer target type".

Related topics:

Previous keywordchar

Next keywordcontinue

   Search this site: