Pointer declared as constant as well as volatile Pointer declared as constant as well as volatile c c

Pointer declared as constant as well as volatile


The const says that the flow of your program isn't going to modify what is pointed to by p. Any attempt to modify the value after dereferencing the pointer will result in a compile-time error:

*p = 'A'; // will not compile

Note that this isn't a particularly strong contract; the value at location 0x30 can still be changed through an aliasing non-const pointer, other than p:

volatile char *q = 0x30;*q = 'A'; // will compile

Another way to break this contract is by casting away the const from p:

*(volatile char *) p = 'A'; // will compile

The volatile, however, doesn't exclude any modifications which could be caused by another thread, the kernel, an asynchronous signal handler or an external device which has access to the same memory space. This way the compiler cannot make the wrong assumption that the value pointed to by p doesn't change and will load it from memory every time it is referenced:

/* The character at 0x30 will be read on every iteration, even if the compiler has proven that the program itself doesn't modify the value at that address.*/while (*p) {    ...}

If the compiler was to erroneously optimise such a construct, it could emit instructions which load the value only once from memory and then keep it in a register. The register is essentially an independent copy and any changes to the original location will not reflect there, and, needless to say, this can cause some very nasty bugs.


Consider a read-only hardware register, of your network card for example.

It might change outside the control of the program, so the compiler is not allowed to cache its value in a register or optimize it away. Thus, volatile.

And it's read-only, so you shouldn't write to it. Thus, const.


First, let me quote the example from C11 standard, chapter ยง6.7.3, Type qualifiers

An object declared

extern const volatile int real_time_clock;

may be modifiable by hardware, but cannot be assigned to, incremented, or decremented.

Also, related footnote (134),

A volatile declaration may be used to describe an object corresponding to a memory-mapped input/output port or an object accessed by an asynchronously interrupting function. Actions on objects so declared shall not be "optimized out" by an implementation or reordered except as permitted by the rules for evaluating expressions.

That means, the value of the variable can be modified by the hardware (through the memory-mapping), but cannot be modified "programatically".

So, the advantage is twofold here,

  • The value whenever used, will be read from the memory (cache-ing not allowed), giving you the latest updated value (if updated).
  • The value, cannot be altered, (written over) intentionally or unintentionally by the program.