typestar

volatile in C

volatile tells the compiler the value can change behind its back.

#include <signal.h>

static volatile sig_atomic_t interrupted = 0;
static volatile unsigned int *const hardware_register =
    (volatile unsigned int *) 0x1000;

void spin_until_flag(void) {
    while (!interrupted) {
    }
}

unsigned int read_twice(void) {
    unsigned int first = *hardware_register;
    unsigned int second = *hardware_register;
    return second - first;
}

How it works

  1. Without it a loop reading a flag may be optimized away.
  2. It disables caching in a register, not much else.
  3. It is not a substitute for an atomic or a lock.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
354
Tokens
67
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 38 seconds.

Type this snippet

Step 1 of 2 in Qualifiers, step 6 of 13 in Unions, bitfields & undefined behavior.

← Previous Next →