Skip to content
StudyFame

volatile Keyword in C

Compilers are clever. To make programs faster, they keep values in CPU registers and skip reading memory when they think the value can't have changed. Usually that's great. But some variables can change behind the program's back: a hardware sensor, a signal handler or another device. For those, you must tell the compiler "don't be clever, read it every time". That is what volatile does.

In this lesson you will learn what volatile means, what goes wrong without it, where it is used (embedded hardware registers, signal handlers), what const volatile means and what volatile does not do.

What You Will Learn

  • What the volatile type qualifier means.
  • How compiler optimization can break code without volatile.
  • The three classic uses of volatile.
  • How to use volatile with a signal handler.
  • The meaning of const volatile and volatile pointers.
  • Why volatile is not a replacement for locks in multithreading.

volatile Keyword in C Explained

Exam definition: volatile is a type qualifier that tells the compiler that a variable's value may change at any time without any action by the code the compiler can see. Therefore the compiler must not optimize accesses to it: every read must fetch the value from memory and every write must store it to memory, in the order written in the program.

Memory trick: Imagine checking a cricket score. A lazy friend looks once and keeps telling you that old score from memory. A good friend checks the TV every time you ask, because the score can change at any moment. volatile turns the compiler into the good friend.

Syntax of volatile

volatile int flag;                 /* the int may change unexpectedly        */
int volatile flag2;                /* same meaning                           */
volatile int *p;                   /* pointer to a volatile int              */
int *volatile q;                   /* the pointer itself is volatile         */
const volatile int status;         /* program can't change it, but it can
                                      still change from outside (read-only
                                      hardware register)                     */
volatile sig_atomic_t got_signal;  /* standard type for signal-handler flags */

Example 1: A volatile Variable in a Loop

Here a volatile variable stands for a sensor value. In real hardware, the sensor changes it; in this demo, the loop changes it so you can see the output.

#include <stdio.h>

volatile int sensor_value = 0;     /* imagine hardware updates this */

int read_sensor(void)
{
    return sensor_value;           /* volatile: always read from memory */
}

int main(void)
{
    int reading, i;

    for (i = 1; i <= 3; i++)
    {
        sensor_value = i * 10;     /* in a real device, hardware writes here */
        reading = read_sensor();
        printf("Reading %d: %d\n", i, reading);
    }

    const volatile int max_limit = 100;   /* program must not change it */
    printf("Limit: %d\n", max_limit);
    return 0;
}

Output

Reading 1: 10
Reading 2: 20
Reading 3: 30
Limit: 100

Code Explanation

  1. volatile int sensor_value tells the compiler the value can change by itself, so every use of sensor_value reads memory.
  2. read_sensor() returns the current memory value. Without volatile, an optimizing compiler might keep an old copy in a register in some situations (see the next section).
  3. The output is the same with or without volatile in this small demo. The difference appears with optimization (-O2) when something outside the code (hardware, a signal) changes the variable.
  4. const volatile int max_limit: the program is not allowed to change it (const), but the compiler must still read it each time (volatile). This pattern is used for read-only hardware status registers.

How volatile Stops Wrong Optimization

Look at this loop that waits for a "data ready" flag set by hardware:

int ready = 0;              /* WITHOUT volatile */

void wait_for_data(void)
{
    while (ready == 0)
        ;                   /* wait */
}

The compiler sees that nothing inside the loop changes ready. With optimization on, it may turn the code into this:

read ready once into a register  ->  0
loop forever: is the register 0?  ->  yes, yes, yes ...   (never reads memory again)

Hardware sets ready = 1 in memory, but the loop never sees it: the program hangs.

Declaring volatile int ready = 0; forces a fresh memory read on every check, so the loop ends as soon as hardware sets the flag.

Where volatile is used

UseWho changes the valueExample
Memory-mapped hardware registersThe devicevolatile unsigned int *const UART_STATUS = (unsigned int *)0x40001000;
Signal handlers / interrupt service routinesThe handler, at any momentvolatile sig_atomic_t stop = 0;
Variables used with setjmp/longjmpA jump back into the functionLocal variables changed after setjmp

Example 2: volatile with a Signal Handler

#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t stop_requested = 0;

void handle_signal(int sig)
{
    (void)sig;
    stop_requested = 1;          /* only set a flag inside a handler */
}

int main(void)
{
    int count = 0;

    signal(SIGINT, handle_signal);   /* SIGINT = Ctrl+C */

    while (!stop_requested)          /* volatile: checked from memory each time */
    {
        count++;
        printf("Working... step %d\n", count);
        if (count == 3)
            raise(SIGINT);           /* send ourselves the signal (like pressing Ctrl+C) */
    }

    printf("Stop requested after %d steps. Cleaning up.\n", count);
    return 0;
}

Output

Working... step 1
Working... step 2
Working... step 3
Stop requested after 3 steps. Cleaning up.
  • signal(SIGINT, handle_signal) means: when Ctrl+C (SIGINT) arrives, call handle_signal instead of killing the program.
  • The handler only sets stop_requested = 1. The main loop, which is not "calling" the handler itself, must see this change, so the flag is volatile.
  • sig_atomic_t is an integer type that can be read and written in one step, so the main loop never sees a half-written value.
  • raise(SIGINT) sends the signal from inside the program so the demo stops by itself; in real life, the user presses Ctrl+C.

Important Points to Remember

  • volatile = "this value may change outside the program's control; always access memory".
  • It stops the compiler from caching, removing or reordering accesses to that variable.
  • Main uses: hardware registers, signal/interrupt handlers, setjmp/longjmp.
  • const volatile: can't be changed by the program, but can change from outside.
  • volatile does not make operations atomic or thread-safe; use mutexes or <stdatomic.h> for threads.
  • volatile can make code slower, so use it only where needed.

Common Mistakes Beginners Make

MistakeWhat happensFix
Hardware flag without volatileLoop hangs when optimization is onDeclare it volatile
Using volatile for thread safetycount++ from two threads still loses updatesUse a mutex or atomic types
Making every variable volatileSlower program, no benefitOnly variables changed from outside
Long work (printf) inside a signal handlerNot safe; may crash or deadlockSet a volatile sig_atomic_t flag only
Thinking const volatile is a contradictionConfusion in examsconst = program can't write; volatile = may change anyway

volatile Practice Questions

  1. What is the volatile keyword in C?
  2. What problem can happen if a hardware flag is not declared volatile?
  3. Name three situations where volatile is needed.
  4. What does const volatile int x; mean?
  5. Does volatile make a variable thread-safe?
Show answers
  1. A type qualifier telling the compiler the variable may change unexpectedly, so it must read/write memory on every access and not optimize those accesses.
  2. The compiler may read it once into a register; the loop never sees the hardware change and runs forever.
  3. Memory-mapped hardware registers, variables shared with signal/interrupt handlers, local variables used across setjmp/longjmp.
  4. The program can't modify x, but its value can still change from outside, so it must be read from memory each time (e.g. a read-only status register).
  5. No. It doesn't make operations atomic; use mutexes or atomic types for threads.

Coding Exercise

Write a program with a volatile sig_atomic_t counter and a handler for SIGINT that increments it. In main, raise SIGINT three times, printing the counter after each, then print "Done".

Show solution
#include <stdio.h>
#include <signal.h>

volatile sig_atomic_t signals_seen = 0;

void on_sigint(int sig)
{
    (void)sig;
    signals_seen++;
    signal(SIGINT, on_sigint);   /* re-install for systems that reset it */
}

int main(void)
{
    int i;

    signal(SIGINT, on_sigint);
    for (i = 1; i <= 3; i++)
    {
        raise(SIGINT);
        printf("After signal %d: counter = %d\n", i, (int)signals_seen);
    }
    printf("Done\n");
    return 0;
}
After signal 1: counter = 1
After signal 2: counter = 2
After signal 3: counter = 3
Done

Quick Quiz: volatile Keyword (MCQ)

  1. volatile tells the compiler to:

    A) Make the variable constant   B) Read the variable from memory every time   C) Store it in a register   D) Make it global

  2. volatile is a:

    A) Storage class   B) Type qualifier   C) Data type   D) Operator

  3. Which type is meant for flags set in signal handlers?

    A) volatile sig_atomic_t   B) static char   C) register int   D) float

  4. const volatile is used for:

    A) Loop counters   B) Read-only hardware status registers   C) String literals   D) Function parameters only

  5. Does volatile guarantee atomic operations between threads?

    A) Yes   B) No   C) Only for int   D) Only on Windows

Show answers
  1. B: read it from memory every time.
  2. B: a type qualifier.
  3. A: volatile sig_atomic_t.
  4. B: read-only hardware status registers.
  5. B: no.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

volatileType qualifier: value may change unexpectedly
EffectNo optimization: every access goes to memory
UsesHardware registers, signal handlers, setjmp/longjmp
Signal flagvolatile sig_atomic_t
const volatileProgram can't write; value can still change
Threadsvolatile is not thread-safe

Frequently asked questions

Why is volatile used in C?
To tell the compiler that a variable can change outside the program's flow (hardware, signals), so it must always read it from memory.
Can a variable be both const and volatile?
Yes. const stops the program from changing it; volatile says it may still change from outside.
Is volatile enough for multithreading?
No. It doesn't provide atomicity or ordering between threads; use mutexes or atomics.

Remember

  • volatile = the friend who checks the score every time.
  • Hardware, handlers, longjmp: volatile. Threads: atomics/locks.

Next Topic

Next lesson: Error Handling in C. You will report and handle errors properly with return values, errno, perror, strerror and exit codes.