if there is a volatile variable passed in a function something like below…
Does this function always return a square value, I mean sometimes can the value change as there is a volatile variable declared.
Basically, I am trying to say is that the variable which is passed is a volatile. Hope, I am clear. But, if I make passing of a by reference that would change the whole scenario… am I right??
volatile int a;
int main()
{
function(a);
return 1;
}
int function b(int a)
{
int x=a;
int y=a;
return x*y;
}
The
volatilequalifier tells the compiler that the variable may change not that it will change. It cannot spontaneously change in any case; something has to cause it to change – even if that cause is external to the code.The code is erroneous in this case (or at least does not exemplify the effect of
volatilein the way perhaps you intended) because the parameter passed tofunction()is not declared volatile. The fact that it has the same name as the global variable is perhaps confusing, but by assigning the global variableato the function argumenta, you have immediately decoupled it from the volatility.If the code were modified (and made valid and compilable) thus:
Then effect of
volatilehere is simply that the compiler will explicitly assignxandywithout applying any optimisations that would otherwise be possible. Without the qualifier, the compiler might otherwise (when optimisations are enabled) reducefunction()to just:and might even in-line the entire function. Further, since the return value of function is not assigned to anything, the compiler would likley optimise the entire code to just
If
ais volatile, then the assignments toxandymust occur iffunction()is called.The purpose of
volatileis to indicate to the compiler that a variable may change outside of the code that the compiler has generated (not that it will change). It is typically used to ensure correct behaviour when a variable references either a hardware register, or memory that is shared between threads, processes, or even processors or cores within a processor. It can also be used to prevent “optimising out” of code that is required, (such as empty busy-wait loop counters for example). In your example (or rather my revision of it),adoes not reference any such entity, so the code will behave as expected, but perhaps be less efficient that it might otherwise be.