cembeddedvolatile

What does this function return


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;

}

Solution

  • The volatile qualifier 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 volatile in the way perhaps you intended) because the parameter passed to function() is not declared volatile. The fact that it has the same name as the global variable is perhaps confusing, but by assigning the global variable a to the function argument a, you have immediately decoupled it from the volatility.

    If the code were modified (and made valid and compilable) thus:

    volatile int a;
    
    int function( void )
    {
        int x=a;
        int y=a;
    
        return x*y;
    }
    
    int main()
    {
       function();
       return 1;
    }
    

    Then effect of volatile here is simply that the compiler will explicitly assign x and y without applying any optimisations that would otherwise be possible. Without the qualifier, the compiler might otherwise (when optimisations are enabled) reduce function() to just:

    int function( void )
    {
        return a * a ;
    }
    

    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

    int main()
    {
       return 1;
    }
    

    If a is volatile, then the assignments to x and y must occur if function() is called.

    The purpose of volatile is 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), a does not reference any such entity, so the code will behave as expected, but perhaps be less efficient that it might otherwise be.