Skip to content
Tutorials Center
My learning

Topics

C Reference ยท Keywords and Statements

The volatile qualifier

Reference for the C volatile qualifier: forcing real memory accesses for hardware registers and signal flags, and why it is not a thread-safety tool.

volatile tells the compiler that an object may change in ways it cannot see, or that reading and writing it has effects of its own. Every access written in the source must really happen, in the order written relative to other volatile accesses. The compiler may not cache the value in a register, merge two reads, or drop a write it thinks is useless.

The classic uses are memory-mapped hardware registers, variables modified by a signal handler (volatile sig_atomic_t), and variables shared with setjmp/longjmp code. It is not a synchronization tool for threads.

C
volatile int ready = 0;
while (!ready) {
    /* each iteration re-reads ready */
}

Try it

C A flag set by a signal handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C Qualifier rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Syntax

C
volatile type name;
volatile type *name;        /* pointer to volatile data */
type *volatile name;        /* volatile pointer */
const volatile type name;   /* read-only here, changeable elsewhere */
Placement Meaning
volatile int x Accesses to x are observable behavior.
volatile int *p The int is volatile; p itself is not.
int *volatile p The pointer is volatile; the int is not.

Undefined behavior: accessing an object defined volatile through a non-volatile lvalue is undefined.

Usage notes

  • Not atomic. volatile int counter; counter++; is still a read-modify-write that can be interrupted. Between threads use _Atomic / stdatomic.h or mutexes; volatile gives neither atomicity nor memory ordering.
  • Signal handlers may portably write only to volatile sig_atomic_t objects and lock-free atomics. See signals.
  • Hardware registers: *(volatile uint32_t *)0x40021000 = 1; is the embedded idiom; each write reaches the device.
  • setjmp/longjmp: local variables modified after setjmp and read after longjmp must be volatile, otherwise their values are indeterminate. See setjmp.
  • Benchmarks: a volatile sink prevents the compiler from deleting the computation you wanted to time.
  • Struct copies of volatile objects may not read each member exactly once; do not rely on struct-wide volatile semantics.
  • Not a substitute for const: they can be combined for read-only status registers.