C Constants
Sometimes you have a value in your program that should never change while the program runs, like the number of days in a week or the value of Pi. In C, you can protect such a value by turning it into a constant. Once a value is marked as constant, the compiler will stop you from accidentally changing it later.
Creating Constants
To create a constant, place the keyword const in front of a normal variable declaration. This tells C that the value is read-only. You must give the constant a value at the moment you declare it, because you will not be allowed to assign to it afterwards.
A simple constant
#include <stdio.h>
int main() {
const int MIN_AGE = 18;
printf("You must be at least %d years old.\n", MIN_AGE);
return 0;
}The program above prints: You must be at least 18 years old. The value 18 is now locked. If you try to change it later in the program, the code will not compile.
You Cannot Change a Constant
The whole point of a constant is safety. If someone (including future you) tries to overwrite the value by mistake, the compiler catches the error instead of letting a bug slip through.
This will cause an error
#include <stdio.h>
int main() {
const int SPEED_LIMIT = 60;
// SPEED_LIMIT = 80; // Error: cannot assign to a const
printf("The speed limit is %d.\n", SPEED_LIMIT);
return 0;
}const vs #define
There is another way to create fixed values in C using the #define directive, which is handled before the code is compiled. Both approaches are common, but they work differently. The table below sums up the main points.
Exercise: C Constants
What does the #define directive actually do with a constant like MAX?