Volatie qualifier can be used by keyword volatile in C/C++. You can define a variable as volatile by adding volatile qualifier just before data type.eg
volatile int a;
Volatile specifies a variable whose value may be changed by processes outside the current program. The meaning of outside of the current program may be Operating System or separate thread in case of multi threading processing.
When we defines a variable as volatile, It does two things
1) The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object.
2) It stops Compiler to perform some optimizations.
As we know that Compiler do some kind of optimizations on the source code before compilation. Below examples explain how a volatile qualifier affects the
Compiler optimizations.
Suppose There is the following Source Code:
test.c
int main() { int a =10; if(a == 10) { printf("Yes\n"); } else { printf("No\n"); } }
Source code after compiler optimizations
test-optimized.c
int main() { int a =10; if(1) { printf("Yes\n"); } else { printf("No\n"); } }
As we can see that in optimized code the condition within IF statement changed by 1(always true),The condition always evaluated as true because value of a
never changed within program. So the output of the program will never change whether variable a changes his value outside of the program.
Now try the same code snippet with volatile qualifier.
volatile-test.c
int main() { volatile int a =10; if(a == 10) { printf("Yes\n"); } else { printf("No\n"); } }
volatile-test-optimized.c
int main() { int a =10; if(a == 10) { printf("Yes\n"); } else { printf("No\n"); } }
Now We defined the variable as volatile So we can see that optimized code does not replace the condition within IF statement. The program now expecting the value of variable a can be change by outside of the program. The output of program will change if the value of variable a modified by Operating System or some other threads.
Note :- Above optimized code are not the exact code optimized by complier. It is only intended to explaining the concept.
Comments
Post a Comment