Understanding "volatile" qualifier in C | Set 2 (Examples) (original) (raw)

Last Updated : 16 Jun, 2026

The volatile keyword in C/C++ is used to inform the compiler that a variable’s value may change at any time without any action being taken by the current code. Because of this, the compiler must avoid optimizing such variables.

Why Do We Need volatile?

The value of a variable may change outside the normal program flow, such as:

1. Hardware or Memory-Mapped I/O (Interrupts / Devices)

In embedded systems, hardware devices can change variable values directly.

**Example:

Without volatile, the compiler may cache the value and never re-read it from memory.

**Problem: The program might always read an old value instead of the updated hardware value.

2. Multithreaded Applications

In multithreading, multiple threads share global variables.

**Example:

Since threads run independently, the compiler may:

This leads to incorrect or stale data being read.

Problems Without volatile

If volatile is not used in such scenarios:

Compiler Optimization Example

To understand how compilers behave, consider GCC behavior:

Case 1: No Optimization

gcc volatile.c -o volatile --save-temps

Case 2: With Optimization (-O3)

gcc -O3 volatile.c -o volatile --save-temps

Case 3: Using volatile

When a variable is declared as:

volatile int local;

Real-World Example

Think of a touchscreen sensor in a mobile phone:

**Solution: Use volatile in driver code

Related Article