Deep Analysis of Const Qualifier in C

前端 未结 9 1003
离开以前
离开以前 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:37

    The compiler determines if the address of the constant is ever needed. If it is not, it is (usually) input inline into the code segment because that's (usually) faster than referencing memory.

    If the address is needed, then the constant is stored as if it were a non-const variable in the current scope (relatively depending upon compiler). That is, global consts generally get stored in your data segment, function (parameter or declared) consts generally get stored on the stack.

    Think of it like a register variable. It's in your CPU's register, if you're familiar with that. It's in your CPU's register until you need its address. Then it's put into addressable space.

    The real question is initialization - if you need its address and is therefore actually allocated, then where is it initialized? There's something for you to ponder.

提交回复
热议问题