Confusion regarding modification of const variable using pointers

前端 未结 1 1871
梦谈多话
梦谈多话 2020-11-30 11:56

Following example added confusion in my understanding. I\'m unable to understand how is it possible to modify the const variable local. Please help me to understand the same

相关标签:
1条回答
  • 2020-11-30 12:18

    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.

    0 讨论(0)
提交回复
热议问题