volatile and const keywords are very confusing from there implementation perspective. Today we will see the basic fundamental difference between the two.
const is pretty straight forward, we will declare a variable const if the value of the variable is not changing during the runtime of the program. It helps in fast execution of the program as compiler caches the value in the cache memory of the CPU.
Eg:
void foo()
{
const int a = 100;
}
Whereas the purpose of volatile is different, when you declare any variable with volatile keyword compiler will not perform any kind of optimization for that variable. The optimization is not done because the value for that variable may change by some external factors which compiler can't detect at runtime.
Eg:
void foo()
{
volatile int a = 100;
while(a)
{
//operation
}
}
In the above example the execution condition of the while loop is constant, if the value of a is not changing inside the loop. Then compiler will try to optimize this conditional statement inorder to minimize the data fetching overhead for the CPU. It will try to replace the above code with something like below.
void foo()
{
volatile int a = 100;
while(1)
{
//code
}
}
But imagine the senario when the value of a is getting changed by some external factors like threading, hardware register of the CPU or by some other means. Then it will end up on giving us some garbage value or even leads to crashing of the program.
So, it's always advisable to use volatile very carefully.
To read more about volatile keyword refer this,
https://en.wikipedia.org/wiki/Volatile_(computer_programming)
Top comments (0)