static variable and stack storage

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.
 
E

Eric Liu

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.
In func2(), static variable a will be initialized when the func2 is first
called. I guess variable a exists in the stack as well.

Can anyone tell me which part of the stack they exist?

Thanks

Eric
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top