C · 5 · Systems C26 / 35 · 74%
volatile, restrict & inline
Three keywords that tell the optimizer what it may and may not assume.
Examples: volatile, restrict, static inline
shortcuts: ← prev · → next · M mark
1
volatile
"This memory can change behind your back — reload it every time."
Example
example
volatile uint32_t *reg = (uint32_t*)0x40021000; // hardware register
while (*reg & BUSY_BIT) { } // without volatile this may loop forever
volatile sig_atomic_t stop = 0; // written by a signal handlerWATCH OUT
volatile is NOT a threading primitive. It gives no atomicity and no memory ordering — use _Atomic or a mutex.
2
restrict
A promise that two pointers never alias, which unlocks big optimizations.
Example
example
void add(size_t n, float * restrict out,
const float * restrict a, const float * restrict b) {
for (size_t i = 0; i < n; i++) out[i] = a[i] + b[i];
} // compiler may now vectorize freelyBreak the promise (overlapping buffers) and the behavior is undefined — memmove exists for that reason.
3
inline
A hint to inline the body; in C it also changes linkage rules.
Example
example
static inline int clampi(int v, int lo, int hi) {
return v < lo ? lo : (v > hi ? hi : v);
} // put it in the header — static inline is the safe idiom4
Quick Check
Do you reach for volatile or an atomic?
Quick check
Two threads increment a shared counter. What do you use?