Embedded systems and IoT

Stage 1 · Lesson 5 of 6

volatile and compiler optimisation

C for embedded

Compilers optimise by assuming a variable only changes when the code they can see changes it. That is false for hardware and for variables an interrupt handler updates. The volatile qualifier tells the compiler that every read and write must really happen, so a waiting for a flag keeps re-reading it instead of checking once.

Code without often works with optimisation off and breaks when you switch to a release build, which makes the bug feel random. volatile does not make access atomic (done in one uninterruptible step): incrementing a shared counter is still a read, a change and a write that an interrupt can split.

Common traptreating volatile as a thread-safety tool rather than only a "do not cache this" instruction.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

Practise

  • Compile and run C for a microcontroller in the browser before your board arrives

Keep handy

Also worth your time

Mark this stage as not done?