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 volatileand 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
volatile int sensor_valuetells the compiler the value can change by itself, so every use ofsensor_valuereads memory.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).- 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. 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
| Use | Who changes the value | Example |
|---|---|---|
| Memory-mapped hardware registers | The device | volatile unsigned int *const UART_STATUS = (unsigned int *)0x40001000; |
| Signal handlers / interrupt service routines | The handler, at any moment | volatile sig_atomic_t stop = 0; |
Variables used with setjmp/longjmp | A jump back into the function | Local 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, callhandle_signalinstead 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 isvolatile. sig_atomic_tis 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
| Mistake | What happens | Fix |
|---|---|---|
| Hardware flag without volatile | Loop hangs when optimization is on | Declare it volatile |
| Using volatile for thread safety | count++ from two threads still loses updates | Use a mutex or atomic types |
| Making every variable volatile | Slower program, no benefit | Only variables changed from outside |
| Long work (printf) inside a signal handler | Not safe; may crash or deadlock | Set a volatile sig_atomic_t flag only |
Thinking const volatile is a contradiction | Confusion in exams | const = program can't write; volatile = may change anyway |
volatile Practice Questions
- What is the volatile keyword in C?
- What problem can happen if a hardware flag is not declared volatile?
- Name three situations where volatile is needed.
- What does
const volatile int x;mean? - Does volatile make a variable thread-safe?
Show answers
- 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.
- The compiler may read it once into a register; the loop never sees the hardware change and runs forever.
- Memory-mapped hardware registers, variables shared with signal/interrupt handlers, local variables used across setjmp/longjmp.
- 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).
- 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)
-
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
-
volatile is a:
A) Storage class B) Type qualifier C) Data type D) Operator
-
Which type is meant for flags set in signal handlers?
A)
volatile sig_atomic_tB)static charC)register intD)float -
const volatileis used for:A) Loop counters B) Read-only hardware status registers C) String literals D) Function parameters only
-
Does volatile guarantee atomic operations between threads?
A) Yes B) No C) Only for int D) Only on Windows
Show answers
- B: read it from memory every time.
- B: a type qualifier.
- A:
volatile sig_atomic_t. - B: read-only hardware status registers.
- B: no.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| volatile | Type qualifier: value may change unexpectedly |
|---|---|
| Effect | No optimization: every access goes to memory |
| Uses | Hardware registers, signal handlers, setjmp/longjmp |
| Signal flag | volatile sig_atomic_t |
| const volatile | Program can't write; value can still change |
| Threads | volatile 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.