What memory area is a const object in C ++?

I do not ask what stack / heap / static is, or what makes them different. I ask, in what area is the const object located?

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; } 

What is the memory area of a , b and c in? and what is their lifespan? Are there differences in C?

What if I take their address?

+5
source share
1 answer

This is not indicated. A good optimizing compiler probably does 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 when compiling your code:

 ; 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, constant values ​​are built directly into machine code. There is no memory, heap or data segment allocated for any of them on the stack.

+6
source

All Articles