What is volatile keyword in C: Explanation and Usage
volatile keyword in C tells the compiler that a variable's value can change at any time outside the program's control, so it should not optimize or cache it. This ensures the program always reads the actual value from memory, useful for hardware or shared memory access.How It Works
Imagine you have a note on your desk that can be changed by someone else at any moment. If you keep looking at your copy of the note without checking the original, you might miss updates. The volatile keyword tells the compiler to always check the original note (memory) instead of using a saved copy (cache).
In programming, compilers often optimize code by storing variable values in registers or assuming they don't change unexpectedly. But some variables, like those linked to hardware or shared between threads, can change without the program knowing. Marking them volatile stops the compiler from making these assumptions, ensuring the program reads the latest value every time.
Example
This example shows a volatile variable that might be changed by an external event, like hardware or another thread.
#include <stdio.h> #include <stdbool.h> volatile bool flag = false; void simulate_external_change() { // Simulate an external event changing the flag flag = true; } int main() { printf("Waiting for flag to become true...\n"); while (!flag) { // Waiting for flag to change } printf("Flag changed!\n"); return 0; }
When to Use
Use volatile when a variable can change unexpectedly outside the normal program flow. Common cases include:
- Reading hardware registers that update independently.
- Variables shared between multiple threads or interrupt handlers.
- Flags or signals set by external events.
Without volatile, the compiler might optimize away repeated reads, causing the program to miss changes and behave incorrectly.
Key Points
- Prevents compiler optimizations that assume variable values don't change unexpectedly.
- Ensures every read accesses the actual memory location.
- Does not make code thread-safe by itself; synchronization is still needed.
- Common in embedded systems and low-level programming.
Key Takeaways
volatile to tell the compiler a variable can change anytime outside program control.volatile does not replace proper synchronization in multithreading.