C volatile Keyword
Example
Create a volatile variable:
volatile int myNum = 15;
myNum = 20;
printf("%d", myNum);
Definition and Usage
The volatile keyword tells the compiler that a variable can change at any time, also by something outside the program code, for example by hardware.
Normally, the compiler can make a program faster by skipping some reads and writes of a variable. With volatile, the compiler must read the value from memory every time it is used, and write it every time it changes.
It is mostly used in programs that work directly with hardware, like the small computers inside devices. In normal programs, you rarely need it.
Related Pages
The _Atomic keyword makes a variable safe to use from many threads. volatile does not do this.
Read more about variables in our C Variables Tutorial.