What is volatile keyword and explain about it ?

Volatile is a qualifier that is applied to a variable when it is declared. It tells the compiler that this value may change at anytime.

  • Volatile keyword cannot remove the memory assignment.
  • It cannot cache variables in registers.
  • It cannot change the order of assignment.

Different possibilities of volatile keyword:

  • volatile int x; and int volatile x; both the statements are possible and same.
  • volatile pointer, structure and union all are possible.
  • volatile structure and union object itself or individual parameters inside structure and union can be volatile.

Practically when the volatile is used ?

  1. Memory mapped peripheral registers. (ex SFR) 
  2. Global variable which is accessed by other functions and interrupt service routine.
  3. Global variable within multi threaded applications. 

Practical example :

int main ()
    int a;

int main ()
    volatile int a;

In these two programs a value will be incremented by one. It may vary based on the memory read

  1. If volatile qualifier is not present, a will be copied from it's actual memory to cache memory and it is read from there before the increment. The cache memory varies to controller to controller. Usually it is r0 to r15 in ARM.
  2. If the volatile qualifier is present, a will not be copied to the cache memory. So that it is always read from the actual memory. That is why a variable which can be changed externally or interrupt usage of volatile is necessary.