How to Use the Volatile Keyword in C++? (original) (raw)
Last Updated : 13 Jun, 2026
The volatile keyword is used to indicate that the value of a variable may change unexpectedly outside the program's normal control flow. It prevents the compiler from applying certain optimizations to that variable and ensures that its value is read from memory whenever it is accessed.
- Prevents compiler optimizations on a variable.
- Commonly used with hardware registers, interrupt handlers, and memory shared with external devices.
- Does not provide thread safety or synchronization.
Syntax
volatile dataType varName;
**where:
- **dataType: specifies the type of the variable (such as int, char, or bool).
- **varName: is the name of the variable being declared as volatile. C++ `
#include using namespace std;
volatile bool dataReady = false;
int main() { cout << "Waiting for data..." << endl;
// Assume dataReady is modified by external hardware
// or an interrupt service routine
dataReady = true;
if (dataReady)
cout << "Data received!" << endl;
return 0;}
`
Output
Waiting for data... Data received!
**Explanation
- dataReady is declared as a volatile variable.
- The compiler is instructed to read its value directly from memory whenever it is accessed.
- This is useful when the variable can be modified by an external source, such as hardware or an interrupt service routine.
- When dataReady becomes true, the program prints "Data received!".
**Time Complexity: O(1), for each lock and unlock operation.
**Auxiliary Space: O(1)