Search code examples
cpointersdeclarationvolatilevariable-declaration

How to interpret volatile when there are multiple levels of indirection


Suppose I have the following

struct my_struct ** value;

I understand the difference between

struct my_struct volatile * other_value; // pointer is volatile

and

struct * volatile other_value; // what pointer points to is volatile

but what is the difference between

struct my_struct * volatile * value;  // call this (1)

and

struct my_struct ** volatile value;  // call this (2)

Is it correct to say that (1) means the pointer that is pointed to by value is volatile and (2) means value is volatile and the pointer it points to and the data that pointer points to is not volatile? Or do I have it backwards?

More generally consider something that might look like this

struct my_struct ***** volatile *** value

which pointer in this "series" of pointers is the volatile pointer? Would it be the pointer that is redirected (is this the correct terminology?) 3 times from value or 4? Put another way, does volatile always operate on the right most value/ptr/statement (what would be the right terminology here?).

For example

struct my_struct ******** volatile value

means value is volatile

struct my_struct ******* volatile * value

means the pointer value points to is volatile

struct my_struct ****** volatile ** value

means the pointer pointed to by the pointer pointed to by value is volatile. And so on. Is my understanding correct?

Edit: I was completely wrong. volatile applies to the left not the right.


Solution

  • The rule of thumb is that the qualifier (volatile or const etc) stick to what's on the left side of it.

    I understand the difference between

    struct my_struct volatile * other_value; // pointer is volatile

    and

    struct * volatile other_value; // what pointer points to is volatile
    ... Or do I have it backwards?

    You have it backwards. The first case makes the struct data volatile, the second case makes the pointer itself volatile.

    struct my_struct ***** volatile *** value

    This means that the left pointer * volatile is volatile qualified.

    In general, reading declarations in C from right-to-left helps:

    • other_value other_value...
    • * other_value ...is a pointer...
    • struct my_struct volatile * other_value ... to struct my_struct volatile.

    Also please note that stupidly, C allows the qualifier in a variable declaration to be placed anywhere. Meaning that volatile int* x; and int volatile* x; are equivalent. There is no sound rationale for why this is allowed, it has just always been like that.