When we define variables in a function the compiler may optimize the code that uses the variable. That is, the compiler may compile the code in a manner that will run in the most efficient way possible. The compiler achieves this by using a CPU register to store the variable’s value rather than storing it in stack
However, if we declare the variable as volatile, then it serves as a warning to the compiler that it should not optimize the code containing this variable. In such a case whenever we use the variable its value would be loaded from memory into register, operations would be performed on it and the result would be written back to the memory location allocated for the variable.
volatile int j ;
Another place where we may want to declare a variable as volatile is when the variable is not within the control of the program and is likely to get altered from outside the program. For example, the variable
volatile float temperature ;
might get modified through the digital thermometer attached to the computer