Volatile Variables

Volatile keyword tells the compiler that the value of the variable changed at any time not by the program but by some external event such as interrupt routines, any thread and memory mapped registers When you have written any volatile variables in the program then compiler is not take the control for this variable because at any time this value may change.
Compiler will not do optimization for volatile variable.

1) Global variables modified by an interrupt service routine outside the scope:
            For example, a global variable can represent a data port (usually global pointer referred   
            as memory mapped IO) which will be updated dynamically. The code reading data port 
            must be declared as volatile in order to fetch latest data available at the port. Failing to 
            declare variable as volatile, the compiler will optimize the code in such a way that it will 
            read the port only once and keeps using the same value in a temporary register to 
            speed up the program (speed optimization). In general, an ISR used to update these 
            data port when there is an interrupt due to availability of new data.

 2) Global variables within multi threaded applications.

Const Volatile:
const volatile means the variable is read only on the program scope but it can be modified from outside of your program scope. This is the restriction on the volatile variable to be modified by inside the program.

This is possible and mostly used in embedded system. The example is Interrupt Status Register. As it is a status register in the program we should not modify this variable. So it should be a constant. But this variable can be changed by the processor or hardware based on the interrupt condition. So when in the program we want to read the value of this variable it should read the actual value without any optimization. For this reason the variable can be declared as volatile too.

1 comment: