I was asked a question in a recent interview there is a function defined below
int square(volatile int * p)
{
return *p**p;
}
I was told that there is some thing wrong is this function and is not good for computing square, I think this is due to volatile, Can anyone explain why?
There may be an assumption that because *p
is a volatile access, its value may differ during every evaluation, and thus you should only evaluate it once:
int q = *p;
return q * q;
That's of course silly design; the function should really be int square(int)
and the caller should say square(*p)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With