Overview - Volatile keyword and why it matters
What is it?
The volatile keyword is a special instruction in embedded C that tells the compiler a variable's value can change unexpectedly. This means the compiler should always read the variable from memory and never optimize it away or cache it in a register. It is used when variables can be changed by things outside the program's normal flow, like hardware or other threads.
Why it matters
Without volatile, the compiler might assume a variable never changes on its own and optimize the code to skip reading it repeatedly. This can cause serious bugs in embedded systems where hardware or interrupts update variables. Using volatile ensures the program always sees the latest value, preventing errors in controlling devices or reading sensors.
Where it fits
Before learning volatile, you should understand basic C variables, memory, and how compilers optimize code. After volatile, you can learn about interrupts, concurrency, and memory barriers to handle complex hardware interactions safely.