0
0
Power-electronicsConceptBeginner · 3 min read

Volatile Keyword in Embedded C: What It Is and How It Works

In Embedded C, the volatile keyword tells the compiler that a variable's value can change unexpectedly, such as by hardware or interrupts. This prevents the compiler from optimizing away reads or writes to that variable, ensuring the program always accesses the actual memory location.
⚙️

How It Works

Imagine you have a mailbox that can be changed by someone else at any time, like a hardware device or an interrupt service routine. If you keep a note of the mailbox's content and never check it again, you might miss updates. The volatile keyword tells the compiler to always check the mailbox directly instead of relying on a saved note.

Normally, compilers try to make programs faster by remembering variable values in registers and skipping repeated memory reads. But for variables linked to hardware or shared with interrupts, their values can change without the program knowing. Marking them volatile stops the compiler from making these assumptions and forces it to read the actual memory every time.

đź’»

Example

This example shows a variable that might be changed by hardware. Without volatile, the compiler might optimize the loop and never see changes to flag.

c
volatile int flag = 0;

void interrupt_handler() {
    flag = 1; // This might be called by hardware interrupt
}

int main() {
    while(flag == 0) {
        // Wait here until flag changes
    }
    // Continue when flag is set
    return 0;
}
🎯

When to Use

Use volatile when a variable can change outside the normal program flow. Common cases include:

  • Hardware registers that update automatically
  • Flags or variables changed by interrupt service routines
  • Shared variables in multi-threaded or multi-core systems

Without volatile, the compiler might optimize away necessary reads or writes, causing bugs that are hard to find.

âś…

Key Points

  • Prevents compiler optimizations that assume variable values don’t change unexpectedly.
  • Ensures every access reads from or writes to actual memory.
  • Essential for hardware interaction and interrupt-driven code.
  • Does not make code thread-safe by itself.
âś…

Key Takeaways

Use volatile for variables changed by hardware or interrupts to avoid incorrect compiler optimizations.
It forces the compiler to always read/write the actual memory location of the variable.
Without volatile, your program might miss changes made outside its normal flow.
volatile does not handle synchronization or atomicity in multi-threaded code.
Always mark hardware registers and interrupt flags as volatile in embedded systems.