volatile
is used to prevent the compiler to optimize any variable.
When any variable is used frequently, the compiler optimizes it and keeps the variables in his memory (there are some specific memory blocks (registers), from there variable is accessibility is fast) to serve its value faster to the program.
Therefore, a volatile
is used to prevent the compiler for any type of optimization on the variable. Volatile variables are used with those variables which are used to communicate with the computer hardware, signals, handlers etc.
Consider the given code below :
//global declaration
unsigned char isDeviceAttached = 0;
//other code segment
int main()
{
//system configuration
//other code segment
//any loop/condition which is using the variable
which(isDeviceAttached)
{
//code to handle particular device
}
//other code
return 0;
}
In the above code, variable isDeviceAtteched
is declared globally and is using frequently in the program. The compiler may optimize it and keep its ‘0’ in the memory to serve it faster.
But, the value of isDeviceAtteched
may change when we attached the device to signal/handler/interrupt function.
If we will not use volatile
above condition loop’s condition will be false always. And if we make it volatile
variable, the actual value will be served to the program.
volatile variable’s declaration :
volatile unsigned char isDeviceAttaced;
volatile variable’s declaration, definition (when it is used it two files)
Definition :
volatile unsigned char isDeviceAtteched =0;
Declaration :
extern volatile unsigned char isDeviceAtteched;