volatile keyword (C)

The volatile keyword in C tells the compiler that a variable’s value may change unexpectedly, typically due to external factors.

Usage

volatile int c = 3;

Prevents Optimization: It prevents the compiler from optimizing out what it may see as unnecessary reads or writes to the variable.

Common Uses: Used in embedded systems, for hardware access, and in multithreading environments.

A Hint to the Compiler, Not the Hardware

The volatile keyword is a directive to the compiler, not to the underlying hardware. It does not affect how the hardware interacts with memory; rather, it affects how the compiler generates code around accesses to the volatile variable.

Try this demo

include <stdlib.h>
int main(void) {
int a = 1;
register int b = 2;
volatile int c = 3;
a++; a++;
b++; b++;
c++; c++;
return(a+b+c);
}
/usr/bin/arm-none-eabi-gcc -S -fverbose-asm -I /usr/include/ \
-c volreg.c -o /dev/stdout

Notice how the compiler does not load variable b again when it adds 1 to it.
Let’s see how the program behaves when we turn on optimization:

/usr/bin/arm-none-eabi-gcc -S -fverbose-asm -I /usr/include/ \
-c volreg.c -o /dev/stdout -O

With optimizations turned on, the compiler removes any code that is inconse-
quential or can be precomputed. But not for volatile variables