Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Embedded C

volatile, const and static in Embedded C

Understand volatile for registers and ISR-shared variables, const for flash tables, static for lifetime and linkage, and how the optimizer can break code without them.

Three small keywords decide whether embedded C code works: volatile, const and static. They look like decoration, yet leaving out volatile is the most common reason a program works in a debug build and fails when you turn on optimization. const decides whether a table costs flash or RAM. static limits names to one file and gives variables a permanent address.

This lesson explains each keyword in terms of what the compiler and the hardware actually do, with a simulation that makes the optimizer's behavior visible.

volatile: "this value can change without you"

The compiler assumes that memory only changes when your code changes it. So it may keep a variable in a CPU register, read it once and reuse the value, or delete a "pointless" write. For ordinary variables that is a brilliant optimization. It is wrong for:

  1. Hardware registers, whose value changes because the hardware changed it, and where each access has an effect (reading a UART data register removes the byte from the FIFO).
  2. Variables shared with an interrupt service routine (ISR), modified by code the compiler cannot see being called.
  3. Variables shared between threads or cores (volatile is not enough there; see below).
  4. Memory-mapped I/O delays, such as a software delay loop that must not be removed.

volatile tells the compiler: every read in the source must be a real read, every write a real write, in the order written.

The classic bug

C
bool data_ready = false;          // missing volatile

void UART_IRQHandler(void) { data_ready = true; }

int main(void) {
    while (!data_ready) { }       // optimizer: data_ready never changes in the loop
    process();                    //            so read it once: infinite loop
}

With optimization on, the compiler sees nothing in the loop that modifies data_ready, hoists the read out of the loop and spins forever. The fix is one word: volatile bool data_ready.

For registers, the pattern is a pointer to volatile:

C
#define UART_DR  (*(volatile uint32_t *)0x40004404u)
#define UART_SR  (*(volatile uint32_t *)0x40004400u)

while ((UART_SR & (1u << 5)) == 0) { }    // wait for RXNE; reread every time
uint8_t b = (uint8_t)UART_DR;             // reading also clears the flag

Read volatile uint32_t * right to left: "pointer to volatile uint32_t". Chapter 4 builds full register maps this way (Memory-Mapped Registers).

Simulating a register that changes by itself

You cannot run a real interrupt here, but you can model a "hardware" status bit that sets itself after a few reads, and see what volatile accesses do. The status_read function below has a side effect (it advances time), like a real peripheral.

C A status register that changes on its own

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

If the compiler were allowed to cache the first value of the status, the loop would never end. Real code uses volatile uint32_t * and the generated machine code contains a load instruction on every iteration.

What volatile does not do

  • It does not make operations atomic. On an 8-bit CPU, a volatile uint16_t takes two reads; an interrupt between them yields a torn value (high byte from before, low byte from after). counter++ on a volatile variable is still three steps (load, add, store).
  • It does not order accesses relative to non-volatile accesses or issue memory barriers; on Cortex-M7 and multi-core chips you may also need barrier instructions (__DMB()).
  • It is not a substitute for locks between tasks of an RTOS; use atomics, critical sections or message queues.
  • It does not mean "slow". Use it only where needed: volatile variables cannot be kept in registers.

A good habit for ISR-shared data: copy the volatile into a local once with interrupts disabled or with an atomic read, then work on the local copy.

Torn reads: why atomicity matters

The next program simulates an 8-bit CPU reading a 16-bit counter one byte at a time while a "timer interrupt" increments it between the two reads.

C Torn read of a 16-bit value on an 8-bit CPU

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The torn value 0x01FF is 511, a number the counter never held. On 32-bit Cortex-M an aligned 32-bit access is atomic, which is one reason ARM chips are friendlier.

const: read-only, and where it lives

const says the program will not modify an object. The compiler can then reject writes, and, importantly for embedded work, a global const object can be placed in flash instead of RAM. A lookup table of 256 bytes declared const uint8_t table[256] costs 256 bytes of flash and none of RAM. Declared without const, it costs 256 bytes of flash (the initial values) and 256 bytes of RAM (the copy).

C
const uint8_t sine_table[8] = {0, 90, 127, 90, 0, 166, 255, 166};   // flash
uint8_t sine_copy[8];                                                // RAM

On Harvard chips like AVR, flash and RAM are different address spaces, so you need PROGMEM and pgm_read_byte() to read the flash copy; on Cortex-M no extra step is needed.

Pointer variants

The position of const relative to * matters:

Declaration Meaning
const uint8_t *p pointer to const data: cannot modify *p, can move p
uint8_t *const p const pointer: cannot move p, can modify *p
const uint8_t *const p neither
volatile const uint32_t *p read-only hardware register (a status or ID register)

volatile const is not a contradiction. const stops your code from writing; volatile tells the compiler that hardware can change it. A device ID or an ADC data register is exactly that.

Use const on function parameters that point to data you only read (void send(const uint8_t *buf, size_t n)); it documents intent and lets callers pass flash tables.

C const pointers, and the compiler objecting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Uncomment either commented line to see the compiler stop you. Catching accidental writes at compile time is cheap insurance.

static: lifetime and visibility

static has two uses and you need both:

  1. At file scope (a global or a function): internal linkage. The name is visible only in this .c file. This keeps module-private state private and avoids name clashes between files.

    C
    static uint8_t rx_buf[64];          // only uart.c can touch it
    static void uart_flush(void) { }    // helper, not exported
    
  2. Inside a function: the variable has static storage duration. It is created once, lives for the whole program, and keeps its value between calls. It lives in .data or .bss, not on the stack.

    C
    uint32_t next_id(void) {
        static uint32_t id = 0;      // initialized once, before main
        return ++id;
    }
    

In firmware, static function-local variables are handy for state in a small function (a debounce counter) but they make a function non-reentrant: two tasks or an ISR calling it share the same variable. Prefer passing a context struct.

Also, embedded code prefers static allocation over malloc: a static buffer has a fixed address, is visible in the linker map file and can never run out unexpectedly at run time.

C A static local keeps state between calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Putting them together

Situation Declaration
Register read/written by hardware volatile uint32_t * (pointer to volatile)
Flag set in an ISR, read in main static volatile bool flag;
Lookup table in flash static const uint8_t table[] = {...};
Module-private buffer static uint8_t buf[64];
Read-only hardware ID register volatile const uint32_t *
Helper function used by one file static void helper(void)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does while (!flag) {} hang forever when flag is set by an ISR and not declared volatile?

    With optimization the compiler assumes no other code modifies flag, hoists the read and loops forever. volatile forces a read on every iteration.
  2. 2. Which is true about volatile?

    volatile controls the compiler's optimizations, not atomicity or locking.
  3. 3. What is the effect of declaring a global lookup table const on a Cortex-M?

    Const globals can live in read-only flash, saving RAM.
  4. 4. What does a static variable declared inside a function do?

    Static storage duration means one instance for the entire run; it just has function scope.

Summary

  • Use volatile for hardware registers and variables shared with ISRs; it forces real reads and writes but is not atomic.
  • Use const for data that never changes so it can stay in flash, and for read-only pointer parameters; volatile const fits read-only hardware registers.
  • static at file scope hides names; static inside functions keeps state across calls but makes functions non-reentrant.
  • Prefer static allocation: fixed addresses, visible in the map file, no run-time failure.

Next: Structs, Unions, Bit-Fields and Endianness