Course contentsShow
← C
Lesson 914 of 1,21913. Advanced CFree lesson

How `volatile` prevents compiler optimization

How volatile prevents compiler optimization

What you'll learn: You will understand how to use the volatile keyword to tell the compiler that a variable's value can change unexpectedly from outside the program's immediate flow.

The Over-Helpful Assistant

Imagine you are baking a cake and checking a thermometer. If you check it and it says 350°F, and you haven't touched the dial, you might assume it’s still 350°F a few seconds later. You might even decide to stop looking at the thermometer altogether to save time.

A C compiler does the same thing. It is obsessed with speed. If it sees you reading a variable inside a loop, but notices that your code never changes that variable, it will "optimize" the code. It might read the value into a CPU register once and simply reuse that stored value forever, rather than checking the actual memory address every time.

Usually, this is great. But what if that "thermometer" is a hardware sensor or a value updated by a different thread? Your program will keep using the old, "cached" value, completely unaware that the real data has changed.

Enter volatile

The volatile qualifier is your way of telling the compiler: "Don't assume you know what's happening here. Every time I ask for this variable, go physically check the memory. Do not cache it, do not skip the read, and do not reorder my instructions."

Here is a common scenario in embedded systems or multi-threaded code:

#include <stdio.h>

int main() {
    // Without 'volatile', the compiler might turn this into an infinite loop
    // because it assumes 'status' never changes within this scope.
    volatile int status = 0; 

    printf("Waiting for hardware signal...\n");

    // The compiler is forced to check the actual memory of 'status' 
    // on every single iteration of this loop.
    while (status == 0) {
        // Imagine a hardware interrupt or another thread 
        // sets 'status' to 1 in the background.
    }

    printf("Signal received!");
    return 0;
}

Why it matters

If we removed volatile from the code above, a high-level optimization might see while (status == 0) and think: "Since status is 0 and nothing in this loop changes it, I'll just treat this as while (true)." Your program would then hang forever, even if the memory at the status address changed to 1.

Use volatile whenever you are dealing with memory-mapped I/O, interrupt service routines, or shared global variables in multi-threaded applications where a value might change without the compiler seeing it happen in the current code block.

Key takeaway

The volatile keyword disables compiler optimizations for a variable, forcing the program to perform a fresh memory read or write every time that variable is accessed.