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

Combining `const` and `volatile`

Combining const and volatile

What you'll learn: How to tell the compiler that a variable’s value can change without your code doing it, while simultaneously preventing your own code from modifying it.

The "Read-Only Sensor" Problem

At first glance, const and volatile seem like opposites. const tells the compiler "this value won't change," while volatile says "this value could change at any millisecond."

However, they actually describe two different perspectives. const is about permission (Can my code change this?), while volatile is about expectation (Can the outside world change this?).

Imagine a hardware clock or a temperature sensor mapped to a specific memory address. You don't want your program to accidentally overwrite the current time—that would be a bug. But you also need the compiler to know that the time updates itself constantly, so the compiler shouldn't "cache" the value in a CPU register to save time.

Using them together

When you combine them, you create a read-only window into a piece of hardware or a shared memory location.

// A read-only hardware register (e.g., a system timer)
// const: My code is not allowed to write to this address.
// volatile: The hardware might change this value at any time.
extern const volatile int *system_timer;

void monitor_timer() {
    int time1 = *system_timer;
    
    // Without volatile, the compiler might think time2 is the same as time1
    // and skip reading the memory again.
    int time2 = *system_timer; 
    
    if (time2 > time1) {
        // The hardware updated the value automatically!
    }
    
    // *system_timer = 0; // ERROR: The 'const' qualifier prevents this.
}

Why this matters

If you only used volatile, your code could accidentally corrupt hardware settings. If you only used const, the compiler would optimize your code by assuming the value never changes, leading your program to "see" the same old value forever, even if the hardware has updated it.

By using both, you tell the compiler: "Keep your hands off this value, but keep your eyes glued to it because it moves on its own."

Key takeaway

const volatile creates a read-only variable that the compiler is forced to re-examine every time it is accessed because an external source (like hardware) can change it.