const says that your program thread will not change what p points to. Any attempt to change the value after dereferencing the pointer will result in a compile-time error:
*p = 'A';
Please note that this is not a particularly strong contract; the value at 0x30 can still be changed using a non-constant anti-aliasing pointer, except for p :
volatile char *q = 0x30; *q = 'A';
Another way to break this contract is to drop const from p :
*(volatile char *) p = 'A';
However, volatile does not exclude changes that may be caused by another thread, kernel, asynchronous signal processor, or external device that has access to the same memory space. Thus, the compiler cannot accept the incorrect assumption that the value pointed to by p does not change and will load it from memory every time it refers:
while (*p) { ... }
If the compiler had to erroneously optimize such a construction, it could generate instructions that load the value only once from memory, and then store it in the register. The register is essentially an independent copy, and any changes in the original location will not be reflected there, and, of course, this can cause some very unpleasant errors.
Blagovest Buyukliev Jul 16 '15 at 13:56 2015-07-16 13:56
source share