All Courses
C Intermediate

Type Qualifiers: const, volatile & restrict

Type qualifiers are keywords prepended to variable declarations to specify how variables can be accessed, optimized, and linked by the compiler.

1. The const Qualifier

The const keyword declares a variable as read-only. Attempting to modify its value directly after initialization will throw a compiler error:

const double PI = 3.14159;
// PI = 3.14; // Compiler error!

Const with Pointers

The placement of the const keyword relative to the asterisk (*) is critical: - Pointer to Const: The data pointed to is read-only, but the pointer address can change. c const int *ptr = &val; // *ptr = 10; // Error! Can't modify value ptr = &other_val; // OK! Pointer address can change - Const Pointer: The pointer address is read-only, but you can modify the data value. c int *const ptr = &val; *ptr = 10; // OK! Can modify value // ptr = &other_val; // Error! Address cannot change

2. The volatile Qualifier

The volatile qualifier tells the compiler that the variable's value can be changed by external hardware or system actions outside the program's control. It forces the compiler to always read and write directly to RAM, preventing it from caching the value inside CPU registers:

volatile int sensor_reading;
// Compiler will not optimize loops checking this variable,
// ensuring the latest hardware state is read every time.
while (sensor_reading == 0) {
    // Wait for hardware sensor signal
}

3. The restrict Qualifier (C99)

Used exclusively on pointer declarations. It is a promise to the compiler that the pointer is the only access channel to the memory block it points to. This allows the compiler to perform aggressive optimizations (like loop vectorization):

void add_arrays(int *restrict a, int *restrict b, int *restrict c, int n) {
    // Restrict guarantees the buffers in memory do not overlap
}