"volatile const int a" vs "const volatile int a"?

Viewed 85

I understood that if we use volatile and const together to a variable indicates that the variable value cannot be changed inside the scope of the code, but can be changed by outside scope — for example, hardware interaction with the variable a.

But what is the difference between the syntax volatile const int a and const volatile int a?

1 Answers

Modifier order doesn't matter when no pointers are involved. Your two examples are equivalent.

If pointers are involved, the order matters only relative to the name of the core type and the *(s). For a variable declaration with placeholders for modifiers A, B, C and D:

<A> int <B> * <C> * <D>

location A or B modifies the int (int const and const int mean the same thing), while location C affects the first * (the second level of indirection), and location D affects the second * (the first level of indirection).

So:

unsigned int * volatile * const x;

means that:

  1. You can't reassign x itself (but you can reassign *x or **x)
  2. *x is volatile (the compiler can't optimize out reads or writes to *x, and can't reorder them relative to other volatile accesses)
  3. **x is unsigned (but neither volatile nor const, though *x being volatile will cause some aspects of volatile to be applied, simply because it's not allowed to cache *x, and therefore can't cache **x either; if your code explicitly cached though, e.g. unsigned int *starxcopy = *x;, then worked with *starxcopy, *starxcopy would be able to cache the pointed-to value, because the value itself is not volatile)
Related