C++ volatile Keyword
Example
Create a volatile variable:
volatile int myNum = 10;
myNum = 20;
cout << myNum;
Definition and Usage
The volatile keyword tells the compiler that a variable can change at any time, also by something outside the program, like hardware (for example a sensor).
Normally, the compiler can make a program faster by keeping a copy of a value, instead of reading it from memory again. With volatile, the program must read the value from memory every time it is used.
You only need volatile in low-level programs, like programs that control hardware. In the example above, myNum works just like a normal variable.
Related Pages
Read more about variables in our C++ Variables Tutorial.