volatile keyword in c


Volatile keyword in C
          The compilation system they always try to reduce the code size and execution time. It is the duty of the programmer to inform the compiler to stop optimizations.Volatile in C informs the compiler to stop optimizing the code .
SYNTAX: (How to Use?)
          For a variable to be volatile , just write the keyword “volatile” before the data type in the variable definition.
For example:
          Volatile int temp;
If we write the volatile after the data type it is also the same
Eg: int volatile temp;
Where to use it?
          A variable can be declared as a volatile whenever the value of the variable changes unexpectedly or the value can be changed by something beyond the control of the program such as concurrently executing thread or an Interrupt Service Routine.
There are three chances where the value of the variable may change unexpectedly:
          1.Memory mapped peripheral registers.
          2.Global variables modified by an Interrupt Service Routine.
          3.Global variables in a multi-threaded environment.       

Let us take an simple example to understand the concept of volatile
Interrupt service routines always set some variable which are used in main function.
int number;
void interrupt()
{
      number=5 ;
}
int main()
{
      int  value ;
      value = number ;
      while(value !=number)
      value = number ;
      return value ;
}

Here the interrupt is used to change the value of the variable “number”.

When the compiler executes the while statement , the optimizer in the compiler may notice that it has read the value already and the      value is still in the register. Instead of reading the value from the memory the compiler may produce a code to read the value from the register which defeats the main aim of this c program. Some compiler may optimize by thinking that as the value of the number is assigned just before the while loop .So the condition in the while loop is always false. In order to avoid optimization make the variable as volatile.

volatile int number;
This will inform the compiler to read the value of the variable “number” always from the memory location.

Comments

  1. website development perth
    We use WordPress as a platform to build dynamic, beautiful, high-performance websites. Get your WP business website started from $1500. We're in Subiaco.

    ReplyDelete

Post a Comment

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

PR, PN and PV Variable in Yocto