Confusion regarding modification of const variable using pointers

This is simply undefined behavior if we look at the C99 draft standard section 6.7.3 Type qualifiers paragraph 4 it says:

If an attempt is made to modify an object defined with a const-qualified type through use
of an lvalue with non-const-qualified type, the behavior is undefined. If an attempt is
made to refer to an object defined with a volatile-qualified type through use of an lvalue
with non-volatile-qualified type, the behavior is undefined.115)

So you can not have any expectations on the results and you should not be doing this.

If we look at paragraph 2 it says:

The properties associated with qualified types are meaningful only for expressions that
are lvalues.114)

and footnote 114 says:

The implementation may place a const object that is not volatile in a read-only region of
storage. Moreover, the implementation need not allocate storage for such an object if its address is never used.

In general the implementation does not have to make const variables read-only but it may but as R.. points out placing an automatic variable in read-only memory would be hard.

Leave a Comment