C examples for Language Basics:Constant
You can define constant variable by adding the const keyword either before or after the data type.
const modifier makes the variable read-only, and you can only assign a value when it is declared.
const int var = 5; /* recommended order */ int const var2 = 10; /* alternative order */
For pointers, const can be used in two ways.
First, the constant pointer means that it cannot point to another location.
int myPointee; int* const p = &myPointee; /* constant pointer */
Second, the constant pointee means that the variable pointed to cannot be modified through this pointer.
const int* q = &var; /* constant pointee */
To declare both the pointer and the pointee as constant.
const int* const r = &var; /* constant pointer & pointee */
Function parameters can be marked as constant to prevent them from being updated by the function.
void foo(const int* x) { if (x != NULL) { int i = *x; /* allowed */ *x = 1; /* compile-time error */ } }