Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

volatile as argument identifier

Tags:

c

pointers

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?

like image 412
Uint32 Avatar asked Mar 11 '23 04:03

Uint32


1 Answers

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).

like image 130
Kerrek SB Avatar answered Mar 20 '23 17:03

Kerrek SB