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:
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.
In C, to define a pointer to a constant value put the const keyword before the pointer type and asterisk:
In C, to define constant pointer to a variable value put the const keyword after the pointer type and asterisk:
Here is the compilation and the output. You should see a warning like "initialization discards 'const' qualifier from pointer target type".