The const qualifier makes an object non-modifiable through the declared object. It is commonly used when a value should remain unchanged after initialization.
#include <stdio.h>
int main()
{
const int maximum = 100;
const float pi = 3.14159f;
printf("%d\n", maximum);
printf("%.5f\n", pi);
return 0;
}
Example Output #
100
3.14159
Explanation #
The variables are declared with const:
const int maximum = 100;
const float pi = 3.14159f;
Their values cannot be modified through these declarations:
maximum = 200; /* Invalid */
pi = 3.14f; /* Invalid */
A const object should normally be initialized when it is declared:
const int value = 10;
A const qualifier applies to the declared type and does not necessarily make every object or memory location involved in an expression immutable.
For example, a pointer can point to const data:
const int *ptr;
Here, the data accessed through ptr cannot be modified through ptr, but the pointer itself can be changed to point somewhere else. Pointer qualifiers are covered separately in the pointer and type-qualifier sections.