static variable and stack storage

Discussion in 'C++' started by Peter van Merkerk, Aug 25, 2003.

  1. "Eric Liu" <> wrote in message
    news:...
    > 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.

    --
    Peter van Merkerk
    peter.van.merkerk(at)dse.nl
    Peter van Merkerk, Aug 25, 2003
    #1
    1. Advertising

  2. Peter van Merkerk

    Eric Liu Guest

    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
    Eric Liu, Aug 26, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Patrick Hoffmann
    Replies:
    3
    Views:
    2,832
    Christian Jan├čen
    Aug 8, 2003
  2. Pavan
    Replies:
    3
    Views:
    430
    Malcolm
    May 28, 2005
  3. sarathy
    Replies:
    2
    Views:
    660
    sarathy
    Jul 17, 2006
  4. Replies:
    2
    Views:
    2,349
    Rolf Magnus
    Feb 27, 2006
  5. arnuld
    Replies:
    2
    Views:
    364
    Phil Carmody
    Aug 8, 2009
Loading...

Share This Page