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.

Syntax

volatile dataType varName;

**where:

#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

**Time Complexity: O(1), for each lock and unlock operation.
**Auxiliary Space: O(1)