C++ volatile


Example

A type qualifier; when applied to a type, produces the volatile-qualified version of the type. Volatile qualification plays the same role as const qualification in the type system, but volatile does not prevent objects from being modified; instead, it forces the compiler to treat all accesses to such objects as side effects.

In the example below, if memory_mapped_port were not volatile, the compiler could optimize the function so that it performs only the final write, which would be incorrect if sizeof(int) is greater than 1. The volatile qualification forces it to treat all sizeof(int) writes as different side effects and hence perform all of them (in order).

extern volatile char memory_mapped_port;
void write_to_device(int x) {
    const char* p = reinterpret_cast<const char*>(&x);
    for (int i = 0; i < sizeof(int); i++) {
        memory_mapped_port = p[i];
    }
}