Deep Analysis of Const Qualifier in C

前端 未结 9 1014
离开以前
离开以前 2020-11-30 08:26

Where does a const variable gets stored exactly and how does it behaviour change? Say for example:

const int i=10; // stores where ?  
main()  
         


        
9条回答
  •  不知归路
    2020-11-30 08:49

    Per the C standard (n1256 draft):

    6.7.3 Type qualifiers
    ...
    3 The properties associated with qualified types are meaningful only for expressions that are lvalues.114)
    ...
    5 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)
    ...
    114) 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.

    115) This applies to those objects that behave as if they were defined with qualified types, even if they are never actually defined as objects in the program (such as an object at a memory-mapped input/output address).

    In short, a const-qualified object may be stored in a different area from non-const-qualified objects, but not necessarily.

    The const qualifier is an instruction to the compiler to reject code that attempts to modify that object directly; attempts to modify the object indirectly (as you do in the second code snippet) results in undefined behavior, meaning any result is possible.

提交回复
热议问题