What if your program misses critical updates because it trusts outdated data?
Why Volatile variables in ISR context in Embedded C? - Purpose & Use Cases
Imagine you have a program that reads a sensor value and updates it inside an interrupt service routine (ISR). You try to read this value in your main program loop without any special care.
Without marking the variable as volatile, the compiler might optimize the code by assuming the variable never changes unexpectedly. This causes the main loop to use a cached value, missing updates from the ISR, leading to wrong or stale data.
Using the volatile keyword tells the compiler that the variable can change at any time, especially from outside the main program flow like in an ISR. This prevents unwanted optimizations and ensures the program always reads the latest value.
int sensor_value; // updated in ISR while(1) { if(sensor_value > 100) { /* do something */ } }
volatile int sensor_value; // updated in ISR while(1) { if(sensor_value > 100) { /* do something */ } }
This concept ensures your program reliably reacts to real-time events by always seeing the latest data changed by interrupts.
In a heart rate monitor device, the pulse count is updated inside an ISR triggered by a sensor. Marking the pulse count variable as volatile ensures the main program always reads the current heart rate.
Without volatile, the compiler may ignore changes from ISRs.
Volatile tells the compiler to always read the variable fresh.
This prevents bugs and ensures correct real-time behavior.