Volatile variables

suggest change

The volatile keyword tells the compiler that the value of the variable may change at any time as a result of external conditions, not only as a result of program control flow.

Every access through a volatile-qualified lvalue is an observable side effect, so the implementation must perform those accesses according to the rules of the abstract machine. This does not make an operation atomic and does not provide synchronization between threads.

#include <stdint.h>

volatile int device_status;
volatile uint8_t *register_address; /* Pointer to a volatile object. */

Two common uses for volatile-qualified objects are:

Let’s see this example:

#include <signal.h>

static volatile sig_atomic_t quit;

static void interrupt_handler(int signal_number)
{
    (void)signal_number;
    quit = 1;
}

int main(void)
{
    if (signal(SIGINT, interrupt_handler) == SIG_ERR) {
        return 1;
    }

    while (!quit) {
        /* Perform work. */
    }

    return 0;
}

The volatile sig_atomic_t type is the portable choice for the narrow case of communication with a signal handler. Signal handlers have many additional restrictions: most library functions are unsafe to call from them. For communication between threads, use atomics or synchronization primitives instead of volatile.

The same problem happens when accessing hardware, as we see in this example:

#include <stdint.h>

volatile uint8_t *status_register =
    (volatile uint8_t *)(uintptr_t)0x1717;

/* Wait for the register to become nonzero. */
while (*status_register == 0) {
    /* Perform other work if appropriate. */
}

The volatile qualification requires an access each time the loop condition is evaluated. The address and access width in real memory-mapped I/O code are platform-specific; obtain them from the hardware and implementation documentation.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents