Can a pointer be volatile?

vishal picture vishal · Oct 22, 2015 · Viewed 11.7k times · Source

Consider the following code:

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

Now, the volatile keyword indicates that the value in a memory location can be altered in ways unknown to the compiler or have other unknown side effects (e.g. modification via a signal interrupt, hardware register, or memory mapped I/O) even though nothing in the program code modifies the contents.

So what exactly happens when we declare a pointer as volatile?

Will the above mentioned code always work, or is it any different from this:

int square(volatile int *p)
{
    int a = *p;
    int b = *p
    return a*b;
}

Can we end up multiplying different numbers, as pointers are volatile?

Or is there better way to do so?

Answer

Damon picture Damon · Oct 22, 2015

Yes, you can of course have a volatile pointer.

Volatile means none more and none less than that every access on the volatile object (of whatever type) is treated as a visible side-effect, and is therefore exempted from optimization (in particular, this means that accesses may not be reordered or collapsed or optimized out alltogether). That's true for reading or writing a value, for calling member functions, and of course for dereferencing, too.

Note that when the previous paragraph says "reordering", a single thread of execution is assumed. Volatile is no substitute for atomic operations or mutexes/locks.

In more simple words, volatile generally translates to roughly "Don't optimize, just do exactly as I say".

In the context of a pointer, refer to the exemplary usage pattern given by Chris Lattner's well-known "What every programmer needs to know about Undefined Behavior" article (yes, that article is about C, not C++, but the same applies):

If you're using an LLVM-based compiler, you can dereference a "volatile" null pointer to get a crash if that's what you're looking for, since volatile loads and stores are generally not touched by the optimizer.