P
Peter van Merkerk
Eric Liu said:Hi,
I am confusing how compiler deals with the static variable in C++.
Let's say there are two functions as below:
class A {};
void func1(){
static int x;
...
}
void func2(){
static A a;
...
}
In func1(), before the main() is executed, x should be initialized. I guess
x exists in the stack.
No, 'x' does not exists on the stack because it is declared static and
doesn't have to be necessarily initialized before main() is executed.
In func2(), static variable a will be initialized when the func2 is first
called. I guess variable a exists in the stack as well.
You guess wrong I'm afraid, also 'a' does not exists on the stack
because it is declared static. The fact that A is class does not change
thing in this respect.
Can anyone tell me which part of the stack they exist?
No part of the stack; they don't exist on the stack.
Note that strictly speaking the C++ standard has no notion of a 'stack'
(other than the std::stack container class in the standard library which
is something totally different). Practially speaking most C++ compiler
do store automatic local variables on the stack, static variables (in-
and outside functions) are stored in a separate memory area.