From this article.
Another use for declaring a variable as
registerandconstis to inhibit any non-local change of that variable, even trough taking its address and then casting the pointer. Even if you think that you yourself would never do this, once you pass a pointer (even with a const attribute) to some other function, you can never be sure that this might be malicious and change the variable under your feet.
I don’t understand how we can modify the value of a const variable by a pointer. Isn’t it undefined behavior?
const int a = 81;
int *p = (int *)&a;
*p = 42; /* not allowed */
The author’s point is that declaring a variable with
registerstorage class prevents you from taking its address, so it can not be passed to a function that might change its value by casting awayconst.By changing potential UB into a constraint violation, a diagnostic becomes required and the error is (required to be) diagnosed at compile time:
Note that array-to-pointer decay on a
registerarray object is undefined behaviour that is not required to be diagnosed (6.3.2.1:3).Note also that taking the address of a
registerlvalue is allowed in C++, whereregisteris just an optimiser hint (and a deprecated one at that).