I just want to know what below function is doing
static int myfunc(int val)
{
return *(volatile int *)val;
}
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
}
请注意,我可能会用一个智能命名的宏来做不同的事情:
#define FORCE_INT_PTR_READ( address ) *(volatile int *)address
您能给我们一个例子吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句