can anyone explain where the constants or const variables stored?

痴心易碎 提交于 2019-12-13 00:38:57

问题


As we all know, C++'s memory model can be divided to five blocks: stack, heap, free blocks, global/static blocks, const blocks. I can understand the first three blocks and I also know variables like static int xx are stored in the 4th blocks, and also the "hello world"-string constant, but what is stored in the 5th blocks-const blocks? and , like int a = 10, where does the "10" stored? Can someone explain this to me?

Thanks a lot.


回答1:


There is a difference between string literals and primitive constants. String literals are usually stored with the code in a separate area (for historical reasons this block is often called the "text block"). Primitive constants, on the other hand, are somewhat special: they can be stored in the "text" block as well, but their values can also be "baked" into the code itself. For example, when you write

// Global integer constant
const int a = 10;

int add(int b) {
    return b + a;
}

the return expression could be translated into a piece of code that does not reference a at all. Instead of producing binary code that looks like this

LOAD R0, <stack>+offset(b)
LOAD R1, <address-of-a>
ADD R0, R1
RET

the compiler may produce something like this:

LOAD R0, <stack>+offset(b)
ADD R0, #10 ; <<== Here #10 means "integer number 10"
RET

Essentially, despite being stored with the rest of the constants, a is cut out of the compiled code.

As far as integer literals constants go, they have no address at all: they are always "baked" into the code: when you reference them, instructions that load explicit values are generated, in the same way as shown above.




回答2:


and , like int a = 10, where does the "10" stored?

It's an implementation detail. Will likely be a part of generated code and be turned into something like

mov eax, 10

in assembly.

The same will happen to definitions like

const int myConst = 10;

unless you try to get address of myConst like that:

const int *ptr = &myConst;

in which case the compiler will have to put the value of 10 into the dedicated block of memory (presumably 5th in your numeration).



来源:https://stackoverflow.com/questions/17983642/can-anyone-explain-where-the-constants-or-const-variables-stored

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!