What is the use of volatile keyword in C/C++? What is the difference between declaring a variable volatile and not declaring it as volatile?
volatile restrict the compiler not to optimize the use of particular variable that is declared volatile in to the code.
Difference between variable with volatile and without it
Variable Without volatile
int main()
{
int a = 5;
while(a == 5) //compiler replace variable **'a'** with 5 as optimization purpose
{
}
if(a==5)//compiler replace **'a'** with 5 as optimization purpose
{
}
return 0;
}
in above code compiler assume that the value of the variable 'a' will always be 5,so compiler replace all 'a' with 5 as optimization purpose.
Variable with volatile
But some variables value changed by outside interrupt,so here we always need to get that variables value directly from Memory.For this purpose we use volatile.
volatile int a=5;
while(a==5) //compiler will npt optimize the variable **'a'** and always get the value of **'a'** from Memory