Reading history

The volatile and restrict Keywords in C

6 min read 1 views

Learn when to use volatile for signal flags and hardware registers, and how restrict lets the C compiler optimise pointer code.

Modern C compilers rewrite your code to make it faster. They keep values in CPU registers, skip reads that look pointless, and reorder loads and stores. Usually that is great. But sometimes you know something the compiler does not: that a value can change behind its back, or that two pointers never point at the same memory. The keywords volatile and restrict pass that knowledge on. One makes the compiler more careful; the other lets it be bolder.

In this lesson you will learn

  • What compiler optimisation can do to ordinary variables
  • When to use volatile: signal handlers and hardware registers
  • volatile sig_atomic_t for flags set by signals
  • What restrict promises, and why it can make code faster
  • Why volatile is not a tool for threads

You should know pointers, the const qualifier and signals.

volatile: “This Can Change Without You”

#include <stdio.h>
#include <signal.h>

/* A flag changed by a signal handler must be volatile sig_atomic_t.
   volatile tells the compiler: this value can change behind your back,
   so read it from memory every time. */
static volatile sig_atomic_t stop_requested = 0;

static void on_signal(int sig) {
    (void)sig;
    stop_requested = 1;
}

int main(void) {
    signal(SIGINT, on_signal);

    long work = 0;
    while (!stop_requested) {
        work++;
        if (work == 1000000)
            raise(SIGINT);       /* pretend the user pressed Ctrl+C */
    }
    printf("loop stopped after %ld steps because the flag changed\n", work);

    /* volatile also stops the compiler from removing "useless" reads and writes */
    volatile int status_register = 0;
    for (int i = 0; i < 3; i++) {
        status_register = i;     /* each write really happens */
    }
    printf("last value written: %d\n", status_register);

    /* const volatile: read-only for the program, but may still change */
    const volatile int sensor = 42;
    printf("sensor reading: %d\n", sensor);
    return 0;
}

Output

loop stopped after 1000000 steps because the flag changed
last value written: 2
sensor reading: 42
  • The loop checks stop_requested, but nothing inside the loop changes it. Without volatile, an optimising compiler may read the flag once, keep it in a register, and turn the loop into an endless one.
  • volatile forces a real memory read on every check. When the signal handler sets the flag to 1, the loop sees it and stops.
  • For flags shared with a signal handler, the C standard recommends exactly volatile sig_atomic_t, a type that can be written in one indivisible step.
  • raise(SIGINT) sends the program a signal, just as pressing Ctrl+C would.
  • Writes to a volatile variable are never removed either. This matters for hardware registers in embedded programs, where each write may switch on an LED or send a byte.
  • const volatile is a value the program must not change, but which can still change by itself, such as a sensor reading.
Use volatile forDo not use it for
Flags set in signal handlersSharing data between threads
Memory-mapped hardware registersMaking code “safer” in general
Local variables changed between setjmp and longjmpCounters updated by several threads

volatile does not make updates atomic and does not order memory between CPU cores. For threads, use mutexes or <stdatomic.h>.

restrict: “These Pointers Do Not Overlap”

#include <stdio.h>
#include <string.h>

/* restrict promises: while this function runs, these pointers do not overlap.
   The compiler can then load and store more freely and produce faster code. */
static void add_arrays(size_t n, double *restrict out,
                       const double *restrict a, const double *restrict b) {
    for (size_t i = 0; i < n; i++)
        out[i] = a[i] + b[i];
}

/* Without restrict, the compiler must assume *total might be one of the prices */
static void sum_into(size_t n, const int *prices, int *total) {
    for (size_t i = 0; i < n; i++)
        *total += prices[i];
}

int main(void) {
    double a[4] = {1.5, 2.5, 3.5, 4.5};
    double b[4] = {10, 20, 30, 40};
    double out[4];
    add_arrays(4, out, a, b);
    printf("out: %.1f %.1f %.1f %.1f\n", out[0], out[1], out[2], out[3]);

    int prices[3] = {120, 80, 45};
    int total = 0;
    sum_into(3, prices, &total);
    printf("total: %d\n", total);

    /* The standard library uses restrict too.
       memcpy's pointers are restrict, so overlapping copies need memmove. */
    char text[] = "abcdef";
    memmove(text + 1, text, 3);
    printf("memmove with overlap: %s\n", text);
    return 0;
}

Output

out: 11.5 22.5 33.5 44.5
total: 245
memmove with overlap: aabcef
  • restrict on a pointer parameter is a promise: while the function runs, the memory reached through this pointer is reached through no other pointer.
  • In add_arrays, that lets the compiler load several items of a and b at once and use fast vector instructions. It knows that writing to out cannot change a or b.
  • sum_into has no restrict. The compiler must assume total might point into prices, so it reloads values more carefully, which can be slower.
  • The standard library uses restrict too. memcpy‘s parameters are restrict, which is exactly why overlapping copies need memmove.
  • Breaking the promise, by passing overlapping pointers to a restrict function, is undefined behaviour. The compiler will not warn you.

Common Mistakes

  1. Using volatile to “fix” a threading bug. It hides the symptom but leaves race conditions.
  2. Forgetting volatile on a flag set by a signal handler, so the main loop never sees the change after optimisation.
  3. Adding restrict to pointers that really can overlap, such as when a caller passes the same array as input and output.
  4. Doing real work in a signal handler. Only set a flag there; do the work in the main code.

Practice Exercises

Exercise 1. An embedded program reads a status register at address 0x40021000. Declare a pointer to it that forces a real read every time.

Show answer
volatile uint32_t *const STATUS = (volatile uint32_t *)0x40021000u;
uint32_t s = *STATUS;    /* always a real read from the hardware */

The pointer itself is const (it never moves), and what it points to is volatile (it can change at any time).

Exercise 2. A function void scale(size_t n, float *restrict dst, const float *restrict src, float k) is called as scale(n, a, a, 2.0f). Is this allowed?

Show answer

No. dst and src point to the same memory, which breaks the restrict promise, so the behaviour is undefined. Remove restrict if in-place use must be supported.

Frequently Asked Questions

Does volatile make my program slower?

A little, for that one variable, because every read and write really goes to memory. That is why you should use it only where it is needed, never on every variable.

Is restrict available in C++?

Not in standard C++. Most C++ compilers offer it under the name __restrict or __restrict__ as an extension. In C, restrict has been standard since C99.

Summary

  • volatile stops the compiler from caching or removing reads and writes.
  • Use it for signal flags (volatile sig_atomic_t) and hardware registers, not for threads.
  • restrict promises that pointers do not overlap, so the compiler can optimise more.
  • Breaking a restrict promise is undefined behaviour.

Next: Generic Programming in C With void Pointers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *