开发者

const int does not take up space?

In a comment to this answer on the usage of Anonymous enum, Oli Charlesworth states that:

const int is immutable, and may not take up any space, depending on what the compiler chooses to do.

If I declare const int i = 10, how is that 10 stored if it "may not take up any space"?

Assuming that an int is 4 bytes, I would presume that at least 4 bytes is reserved to store 1开发者_JAVA百科0 as a const int.


The compiler is free to optimise code as it sees fit, so long as the resulting code offers the same observable side effects.

So variables may be optimised to only exist in registers, or replaced with immediate values. In pseudo-machine-code:

SET 10, eax
ST eax, &i    # Initialise i

...

LD &i, eax    # Add i to ebx
ADD eax, ebx, ebx

could become:

SET 10, eax
ADD eax, ebx, ebx

or even just:

ADD 10, ebx, ebx


Unless you use i in a way that requires an address, the compiler will typically just use it at compile time, and at run time all that will be left it the 10, not a variable.

In particular, since a const doesn't change, there's no need to actually store it in memory unless you do something like passing it to a function that takes a parameter by reference.


Well, it's a little misleading to say that it will take no space, as the value of course will still remain in the instruction space in memory, but no space will be assigned to store the variable as the data type in question. It might be more appropriate to say that the minimum amount of memory possible, which I think is what your reaction is pointing to.


Compiler may substitute number 10 everytime it needs to read i, instead of reading the stored value.


It might be part of the code, and be used as a constant immediate value (such as #define FIVE 5) for example.


The compiler might simply replace all occurrences of i in your code by the constant 10. No i any more, hence no space requirements, it costs the same (if the compiler is not plain dumb or sees you casting away the const) as using magic numbers, just makes for much more readable code. With small constants, it may be able to fold them into the assembly instructions.


It will most likely take up space if you declare it in the global namespace. If you declare it in a function body, or declare it 'static' somewhere, the compiler is free to remove it. If you declare it globally, the compiler has no way of knowing if the constant is referenced from another translation unit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜