On local and global static variables in C++

2020-01-27 03:50发布

C++ Primer says

Each local static variable is initialized before the first time execution passes through the object's definition. Local statics are not destroyed when a function ends; they are destroyed when program terminates.

Are local static variables any different from global static variables? Other then the location where they are declared, what else is different?

void foo () {   
    static int x = 0;
    ++x;

    cout << x << endl;
}

int main (int argc, char const *argv[]) {
    foo();  // 1
    foo();  // 2
    foo();  // 3
    return 0;
}

compare with

static int x = 0;

void foo () {   
    ++x;

    cout << x << endl;
}

int main (int argc, char const *argv[]) {
    foo();  // 1
    foo();  // 2
    foo();  // 3
    return 0;
}

标签: c++ static
7条回答
叛逆
2楼-- · 2020-01-27 04:20

The main or most serious difference is time of initialization. Local static variables are initialized on first call to function where they are declared. The global ones are initialized at some point in time before the call to main function, if you have few global static variables they are intialized in an unspecified order, which can cause problems; this is called static initialization fiasco.

查看更多
登录 后发表回答