Skip to main content
The const keyword in C is a type qualifier that dictates an object’s value is immutable after its initial declaration. It instructs the compiler to treat the variable as read-only, triggering a compilation error if subsequent code attempts to modify the object’s state through direct assignment, increment, or decrement operations.

Syntax and Initialization

In C, unlike C++, a const variable is not strictly required to be initialized at the point of declaration. However, because it cannot be assigned to later, an uninitialized block-scope const variable will permanently hold an indeterminate value. An uninitialized file-scope const variable is zero-initialized via tentative definitions. The const qualifier can be placed before or after the type specifier.

Pointer Semantics

The interaction between const and pointers is dictated by the position of the const keyword relative to the asterisk (*). 1. Pointer to Constant Data The data being pointed to cannot be modified through the pointer, but the pointer itself can be reassigned to point to a different memory address.
2. Constant Pointer to Mutable Data The pointer’s memory address is locked, but the data at that address can be modified.
3. Constant Pointer to Constant Data Both the pointer’s address and the data it points to are strictly immutable.

Typedef and Pointer Interaction

A critical semantic distinction occurs when applying const to a typedef of a pointer. The const qualifier applies to the alias itself (the pointer), not the underlying type. This results in a constant pointer to mutable data (Type * const), rather than a pointer to constant data (const Type *).

Memory Allocation and Linkage

The storage duration and memory segment of a const variable depend on its scope:
  • Global/Static Scope: Variables declared const at file scope or with the static keyword are typically allocated in the read-only data segment (.rodata) of the compiled binary. The operating system enforces hardware-level memory protection on this segment.
  • Local Scope: Automatic const variables declared inside a block reside on the stack. The immutability is enforced purely by the compiler’s semantic analysis, not by hardware memory protection.
By default, global const variables in C possess external linkage (unlike C++, where they default to internal linkage). They can be accessed across translation units using the extern keyword.

Constant Expressions vs. Const Variables

In C, a const-qualified variable is evaluated at run-time, not compile-time. It does not constitute a true “constant expression.” Consequently, a const variable cannot be used in contexts requiring strict compile-time evaluation, such as case labels or global array bounds.

Undefined Behavior (UB)

Attempting to bypass the const qualifier by casting it away results in Undefined Behavior if the underlying object was originally declared as const.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More