`volatile` — C++ Keyword
`volatile` — C++ Keyword
The volatile keyword in C++: prevents the compiler from optimizing away accesses to a variable.
`volatile` — C++ Keyword
The volatile keyword in C++: prevents the compiler from optimizing away accesses to a variable.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
volatileMarks a variable as potentially modifiable by external means (hardware registers, signal handlers, other threads without synchronization). The compiler must not cache or eliminate reads/writes to volatile objects.
volatile Type name;
volatile Type* ptr;
return-type func() volatile; // volatile member function
#include <cstdint>
// Memory-mapped hardware register
volatile std::uint32_t* const STATUS_REG =
reinterpret_cast<volatile std::uint32_t*>(0x4000'0008);
void wait_for_ready() {
// Without volatile, the compiler might hoist the read out of the loop
while (!(*STATUS_REG & 0x1)) {
// busy-wait
}
}
// Signal handler pattern
#include <csignal>
volatile sig_atomic_t g_stop = 0;
void handler(int) { g_stop = 1; }
volatile does not provide thread safety or memory ordering guarantees — use std::atomic for inter-thread communication.setjmp/longjmp interactions.volatileint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}