Which memory area is a const object in in C++? [closed]

梦想的初衷 提交于 2019-12-23 11:09:08

问题


I'm not asking what stack/heap/static mean or what is the different between them. I'm asking which area a const object in?

C++ code:

#include <cstdio>

using namespace std;

const int a = 99;

void f()
{
    const int b = 100;
    printf("const in f(): %d\n", b);
}

int main()
{
    const int c = 101;
    printf("global const: %d\n", a);
    f();
    printf("local const: %d\n", c);
    return 0;
}

which memory area are a, b, and c in? and what are the lifetime of them? Is there any differences in C language?

What if I take their address?


回答1:


That's not specified. A good optimizing compiler will probably not allocate any storage for them when compiling the code you show.

In fact, this is exactly what my compiler (g++ 4.7.2) does, compiling your code to:

; f()
__Z1fv:
LFB1:
        leaq    LC0(%rip), %rdi
        movl    $100, %esi
        xorl    %eax, %eax
        jmp     _printf
LFE1:
        .cstring
LC1:
        .ascii "global const: %d\12\0"
LC2:
        .ascii "local const: %d\12\0"

; main()
_main:
LFB2:
        subq    $8, %rsp
LCFI0:
        movl    $99, %esi
        xorl    %eax, %eax
        leaq    LC1(%rip), %rdi
        call    _printf
        call    __Z1fv
        movl    $101, %esi
        xorl    %eax, %eax
        leaq    LC2(%rip), %rdi
        call    _printf
        xorl    %eax, %eax
        addq    $8, %rsp
LCFI1:
        ret

As you can see, the values of the constants are embedded directly into the machine code. There is no memory on the stack, the heap or the data segment allocated for any of them.



来源:https://stackoverflow.com/questions/15859643/which-memory-area-is-a-const-object-in-in-c

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