c++ - Can indirect change of volatile const be treated as undefined behavior? -


does volatile write volatile const introduce undefined behavior? if drop volatile when writing?

volatile const int x = 42; const volatile int *p = &x; *(volatile int *)p = 8; // line introduce undefined behavior? *(int *)p = 16; // , one? 

compilable code

it undefined behavior (for both statements) attempt modify "initial" const object. c11 (n1570) 6.7.3/p6 type qualifiers (emphasis mine):

if attempt made modify object defined const-qualified type through use of lvalue non-const-qualified type, behavior undefined.

for completeness may worth adding, standard says that:

if attempt made refer object defined volatile-qualified type through use of lvalue non-volatile-qualified type, behavior undefined.

hence latter statement, is:

*(int *)p = 16; 

is undefined second phrase (it's "double ub").

i believe rules same c++, don't own copy of c++14 confirm.


Comments