0 day streak
c / intermediate
Snippet

The volatile Type Qualifier

The 'volatile' keyword tells the compiler that a variable's value can change at any time without any action being taken by the code nearby. This prevents the compiler from applying optimizations that might skip reading the memory location, which is crucial for memory-mapped I/O or signal handling.

snippet.c
c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
// Imagine this variable is modified by hardware or a signal handler
volatile int status_flag = 0;
void wait_for_ready() {
printf("Waiting...\n");
while (status_flag == 0) {
// The compiler is forced to reload status_flag from memory in every iteration
}
printf("Ready!\n");
}
int main() {
// status_flag = 1; // In a real scenario, this would happen externally
return 0;
}
Breakdown
1
volatile int status_flag = 0;
Declares an integer that the compiler must not optimize or cache in registers.
2
while (status_flag == 0)
Ensures the loop checks the actual memory address every time, even if it seems redundant to the compiler.