Home / Learn Chip Programming / volatile, const, static and restrict

volatile, const, static and restrict

Four small keywords prevent many of the nastiest embedded bugs.

In shortFour small keywords prevent many of the nastiest embedded bugs.

Theory in plain words

volatile problemWithout volatilewhile(!flag); compiled as an endless loopflag read once into a registerISR sets flag but loop never sees itWith volatileevery read goes to memoryloop exits after ISR sets flagslightly slower, but correct
volatile problem

What it is

volatile: value may change outside the code flow. const: read only (and can live in flash). static: file-private or persistent local. restrict: pointers do not overlap.

Why we use it

Without volatile the compiler caches a flag in a register and your loop never ends. Without const your lookup tables eat precious RAM.

How it works

Mark ISR-shared variables and registers volatile. Mark tables and read-only parameters const. Use static for internal functions and variables to avoid name clashes.

Where it is used

  • ISR flags and hardware registers
  • Lookup tables in flash
  • Library design

Why volatile matters

Optimiser simulationTry it Yourself

Without volatile the compiler may keep the old value in a register, so the main loop never sees the ISR change.

Correct usage
volatile uint8_t rx_flag;                         // set in ISR, read in main
const uint8_t sine_table[8] = {0,90,127,90,0,166,128,166};   // const: stays in flash
static uint32_t tick_count;                       // static: only visible in this file
void ISR_uart(void) { rx_flag = 1; }
int main(void) { while (!rx_flag) { } /* wait */ }
Careful:volatile does not make an operation atomic. A 32 bit counter on an 8 bit AVR is read in 4 steps; disable interrupts around the read or use an atomic type.

Quick quiz

1. Which variable must be volatile?

2. const arrays on AVR...