Understanding "volatile" qualifier in C | Set 2 (Examples) (original) (raw)
Last Updated : 16 Jun, 2026
The volatile keyword in C/C++ is used to inform the compiler that a variable’s value may change at any time without any action being taken by the current code. Because of this, the compiler must avoid optimizing such variables.
- It prevents compiler optimization on specific variables
- Ensures the latest value is always read from memory
- Commonly used in multithreading and hardware-level programming
Why Do We Need volatile?
The value of a variable may change outside the normal program flow, such as:
1. Hardware or Memory-Mapped I/O (Interrupts / Devices)
In embedded systems, hardware devices can change variable values directly.
**Example:
- A sensor updates a memory location
- An interrupt service routine (ISR) modifies a variable
Without volatile, the compiler may cache the value and never re-read it from memory.
**Problem: The program might always read an old value instead of the updated hardware value.
2. Multithreaded Applications
In multithreading, multiple threads share global variables.
**Example:
- Thread A updates a variable
- Thread B reads the same variable
Since threads run independently, the compiler may:
- Store the variable in a register
- Never refresh it from memory
This leads to incorrect or stale data being read.
Problems Without volatile
If volatile is not used in such scenarios:
- The compiler may cache variables in registers
- Updates from other threads may not be visible
- Interrupt-driven changes may be ignored
- Code may behave correctly only in debug mode, not in optimized builds
Compiler Optimization Example
To understand how compilers behave, consider GCC behavior:
Case 1: No Optimization
gcc volatile.c -o volatile --save-temps
- Compiler does not optimize aggressively
- Variable updates are reflected correctly
- Output shows expected results
Case 2: With Optimization (-O3)
gcc -O3 volatile.c -o volatile --save-temps
- Compiler applies strong optimizations
- May ignore changes to non-volatile variables
- Value may remain unchanged due to caching
Case 3: Using volatile
When a variable is declared as:
volatile int local;
- Compiler is forced to always read from memory
- Optimizations are disabled for that variable
- Latest value is always fetched
Real-World Example
Think of a touchscreen sensor in a mobile phone:
- Hardware continuously updates touch coordinates
- Driver must always read fresh values
- If cached, incorrect touch position is read
**Solution: Use volatile in driver code