0
0
CConceptBeginner · 3 min read

What is volatile keyword in C: Explanation and Usage

The volatile keyword in C tells the compiler that a variable's value can change at any time outside the program's control, so it should not optimize or cache it. This ensures the program always reads the actual value from memory, useful for hardware or shared memory access.
⚙️

How It Works

Imagine you have a note on your desk that can be changed by someone else at any moment. If you keep looking at your copy of the note without checking the original, you might miss updates. The volatile keyword tells the compiler to always check the original note (memory) instead of using a saved copy (cache).

In programming, compilers often optimize code by storing variable values in registers or assuming they don't change unexpectedly. But some variables, like those linked to hardware or shared between threads, can change without the program knowing. Marking them volatile stops the compiler from making these assumptions, ensuring the program reads the latest value every time.

💻

Example

This example shows a volatile variable that might be changed by an external event, like hardware or another thread.

c
#include <stdio.h>
#include <stdbool.h>

volatile bool flag = false;

void simulate_external_change() {
    // Simulate an external event changing the flag
    flag = true;
}

int main() {
    printf("Waiting for flag to become true...\n");
    while (!flag) {
        // Waiting for flag to change
    }
    printf("Flag changed!\n");
    return 0;
}
Output
Waiting for flag to become true... Flag changed!
🎯

When to Use

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

  • Reading hardware registers that update independently.
  • Variables shared between multiple threads or interrupt handlers.
  • Flags or signals set by external events.

Without volatile, the compiler might optimize away repeated reads, causing the program to miss changes and behave incorrectly.

Key Points

  • Prevents compiler optimizations that assume variable values don't change unexpectedly.
  • Ensures every read accesses the actual memory location.
  • Does not make code thread-safe by itself; synchronization is still needed.
  • Common in embedded systems and low-level programming.

Key Takeaways

Use volatile to tell the compiler a variable can change anytime outside program control.
It prevents the compiler from caching or optimizing away reads to that variable.
Commonly used for hardware registers, shared memory, and interrupt flags.
volatile does not replace proper synchronization in multithreading.
Always read volatile variables directly from memory to get the latest value.