tags:

views:

322

answers:

2

Is there a difference between declaring a static variable outside of a function and declaring a static variable inside a function?

Also, what's the difference between declaring a variable as static and just declaring an extern variable?

+4  A: 

The difference is that the static variable inside the function is visible inside the function only, whereas the static variable outside may be seen by any function from its point of declaration to the end of the translation unit.

Otherwise, they behave the same.

Declaring a variable outside of a function without the keyword static means it is visible (accessible) outside the file (translation unit) where it is defined (as well as from the point of definition to the end of the translation unit). If you declare a variable as extern, it means that there is a definition somewhere else - possibly in the same translation unit, but more likely in another. Note that it is possible to declare an extern variable inside a function, but it can only be defined outside of a function.

Jonathan Leffler
A: 

First Example:

class SoTest
{
public:
    SoTest(const char *name)
    {
        printf("C'tor called of %s\t(%#x) object\n",name,this);
    }
    static SoTest ClassStaticObj;
};

static SoTest CStaticObj("CStaticObj");
SoTest SoTest::ClassStaticObj("ClassStaticObj");

void function()
{
    for (int i = 0; i < 2;i++)
    {
        static SoTest FunctionStaticObj("FunctionStaticObj");
            SoTest FunctionObj("FunctionObj");
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    printf("enter main\n");
    function();
    function();
    getchar();;
    return 0;
}

produces:

    C'tor called of CStaticObj      (0x419168) object
C'tor called of ClassStaticObj  (0x419169) object
enter main
C'tor called of FunctionStaticObj       (0x419160) object
C'tor called of FunctionObj     (0x12fe77) object
C'tor called of FunctionObj     (0x12fe77) object
C'tor called of FunctionObj     (0x12fe77) object
C'tor called of FunctionObj     (0x12fe77) object

Now your question(s)

Is there a difference between declaring a static variable outside of a function and declaring a static variable inside a function?

Those are completely different issues static variable / function outside function is not visible outside compilation unit.

static variable inside function is allocated in global data and is initialized only once during first occurance (see that FunctionStaticObj was initialized after main in contradiction to other objects.

Also, what's the difference between declaring a variable as static and just declaring an extern variable?

Again static means not visible outside compilation unit.

extern means "it's not defined here, although in different compilation unit and linker will manage it" so you can make as many extern declarations as you want but only one non extern definition.

XAder