2012年12月21日 星期五

[c] Local, Global, Static Variables

[c] Local, Global, Static Variables

int globalVar;

void foo1()
{
    int localVar = 0;
    static int staticVar = 0;

    localVar++;
    staticVar++;
    globalVar++;

    printf("[foo1] local: %d, static: %d, global: %d\n",
        localVar, staticVar, globalVar);
}

void foo2()
{
    int localVar = 0;
    static int staticVar = 0;

    localVar++;
    staticVar++;
    globalVar++;

    printf("[foo2] local: %d, static: %d, global: %d\n",
        localVar, staticVar, globalVar);

}

int main()
{
    foo1();
    foo2();

    foo1();
    foo2();
}


Output:
1
2
3
4
[foo1] local: 1, static: 1, global: 1
[foo2] local: 1, static: 1, global: 2
[foo1] local: 1, static: 2, global: 3
[foo2] local: 1, static: 2, global: 4



Ref :
http://www.ptt.cc/bbs/C_and_CPP/M.1313555623.A.B58.html

沒有留言:

張貼留言