2

I have the following function implementation that checks for NULL pointer. This is a part of Linux driver, C code:

bool is_null_ponter(volatile void* ptr)
{
  return (NULL == ptr)? true : false;
}

What is the advantage of volatile in that case? Why not to put it in a register?

Thank you.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
  • See http://stackoverflow.com/questions/3604569/what-kinds-of-optimizations-does-volatile-prevent-in-c/3604599#3604599, an answer to a similar (but not duplicate, IMHO) question – jonsca Aug 08 '11 at 07:11

1 Answers1

9

The volatile helps that any pointer can be passed to the function without error or warning even if it is volatile qualified.

But this is bogus, the driver you see seems not to be written very professionally.

First, to be complete such a pointer should also be const qualified, only then it would capture really all pointers.

Then, there is no use case for such a function at all. In a _Bool context (here !ptr) pointers naturally lead to the correct answer, this is specified by the standard. Doing it differently as you see here is probably much frowned upon in the kernel community and I guess that this driver has not been reviewed properly.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • 1
    I agree: the first thought that crossed my mind when I saw this was, "I'd like to go look at the revision history to see who put this little gem into the Linux repo." – Crashworks Aug 08 '11 at 07:28
  • I have a feeling this code was meant to be a pointer to a volatile variable (so the pointer should be deref'd every read), not a volatile pointer, which gets back to 'not to be written very professionally' – Necrolis Aug 08 '11 at 08:45