Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 749
imsrch Avatar asked Apr 07 '13 06:04

imsrch


1 Answers

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.

like image 125
NPE Avatar answered Oct 31 '22 04:10

NPE