0 day streak
c / intermediate
Snippet

The volatile Qualifier for Hardware Access

The 'volatile' keyword tells the compiler that a variable's value can change at any time without any action being taken by the code. This prevents the compiler from performing optimizations like caching the value in a register.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
void wait_for_ready(volatile int* status_reg) {
while (*status_reg == 0) {
// Busy wait - compiler cannot optimize this loop away
}
printf("Hardware is ready!\n");
}
int main() {
int fake_reg = 0;
// In real scenarios, this would be a memory-mapped I/O address
// wait_for_ready(&fake_reg);
return 0;
}
Breakdown
1
volatile int* status_reg
Indicates that the memory pointed to by status_reg is subject to external changes (e.g., hardware or interrupts).
2
while (*status_reg == 0)
Without 'volatile', a compiler might assume the value never changes and turn this into an infinite loop or remove it.