I would say that the practical rule is that the value of your variable can be changed at any time at runtime, and you don't know when, use the volatile keyword. This includes interruptions. For example, you have an interrupt callback function that counts how many times a user has pressed something on the keyboard. Your program does not know WHEN the user presses a button on the keyboard, so the counter variable must be declared with the volatile keyword.
As mentioned earlier, it disables some compiler optimizations for the variable. For instance:
int a = 5; while(a == 5){
The compiler optimizes the while(a == 5) statement into while(true) , because it sees that the variable a cannot change at run time, and it does not make sense to check the value of a each cycle. So you end up in an endless loop. But if you add the volatile keyword:
volatile int a = 5; while(a == 5){
You simply tell the compiler to leave the variable as it is. Do not make any optimizations, some interrupts can change its value. And on this, everything works just fine.
source share