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.
To create a constant in C, put the keyword const before or after the type of the variable:
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
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
In C, to define a pointer to a constant value put the const keyword before the pointer type and asterisk:
const float *ptr_to_constant = &_pi;
In C, to define constant pointer to a variable value put the const keyword after the pointer type and asterisk:
int* const constant_ptr = &count;
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".