5

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?

imsrch
  • 1,152
  • 2
  • 11
  • 24

1 Answers1

7

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • What if `a` or `b` is a very complex user-defined type? – imsrch Apr 07 '13 at 06:45
  • actually, since the code itself is in memory for every running programm, it is somewhere in memory .. – scones Apr 07 '13 at 06:49
  • @user1477871: It depends. You are asking question that are impossible to answer specifically. – NPE Apr 07 '13 at 06:49
  • @scones: The last sentence of my answer spells out which memory areas specifically I am talking about. – NPE Apr 07 '13 at 06:50
  • @NPE how do you produce such output? this is not simply disassembly that I can do in Netbeans? – 4pie0 Apr 07 '13 at 14:39