Home / Learn Chip Programming / volatile, const, static and restrict
volatile, const, static and restrict
Four small keywords prevent many of the nastiest embedded bugs.
Theory in plain words
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
Without volatile the compiler may keep the old value in a register, so the main loop never sees the ISR change.
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 */ }Quick quiz
1. Which variable must be volatile?
It changes outside normal program flow.
2. const arrays on AVR...
AVR has separate address spaces; use PROGMEM.