C Programming • C17 baseline, standards-specific features labeled
const, volatile, restrict, and Aliasing
Use type qualifiers to express access constraints and optimization contracts accurately.
const prevents modification through a particular lvalue. volatile is for accesses whose behavior is externally observable, such as certain device registers; it is not thread synchronization. restrict is a promise about pointer-based access during a scope, and violating that promise can make behavior undefined.
Example
#include <stddef.h>
void add_vectors(size_t count,
const float *restrict left,
const float *restrict right,
float *restrict output) {
for (size_t i = 0; i < count; ++i) {
output[i] = left[i] + right[i];
}
}
What to expect
The restrict-qualified interface promises that the accessed input and output regions do not overlap in a way that violates the restrict contract.
Key idea: Only use restrict when callers can uphold its aliasing promise; use atomics or locks for inter-thread coordination.