Volatile as argument identifier

In a recent interview I was asked a question, is there a function defined below

int square(volatile int * p)
{
    return *p**p;
}

I was told that there is some kind of error in this function, and it is not suitable for calculating the square, I think this is due to variability. Can anyone explain why?

+4
source share
1 answer

There may be an assumption that since it *pis volatile access, its value may differ during each assessment, and therefore you should evaluate it only once:

int q = *p;
return q * q;

This, of course, is a stupid design; the function must be valid int square(int), and the caller must say square(*p).

+7
source

Source: https://habr.com/ru/post/1654240/


All Articles