Why does this function cast an int argument to a volatile pointer and immediately dereferences it?

c

Solution

If val is a pointer when you pass it to this function, it makes sure that the value pointed by this pointer is read and returned to the caller.

I suspect this might be a trick for embedded devices, where sometimes the operation of reading a value at an address has some effect on the hardware. For instance, reading from an hardware FIFO will pop the read value from the FIFO.

Marking here the pointer as volatile make the compiler not optimize the read if it detects that the value is not used.

Example:

#define FIFO_ADDRESS 0x800050

static int myfunc(int val)
{
    return *(volatile int *)val; // the address *will* be read
}

static int bad( int val )
{
    return *(int*)val; // might be optimized to nop()  
                       // by the compiler if the value 
                       // is not used by the caller
}

int main(){
   bad( FIFO_ADDRESS );    // could be NOP since return value is not used

   myfunc( FIFO_ADDRESS ); // *WILL* perform a READ operation on the FIFO, 
                           // even though the result is not used, because 
                           // of the volatile keyword

}

Note that I would do it differently, probably with a smartly named macro:

#define FORCE_INT_PTR_READ( address ) *(volatile int *)address 

Could you give us an example of usage in your case?

Problem

I just want to know what below function is doing ``` static int myfunc(int val) { return *(volatile int *)val; } ```

Original source