How can I understand this static local variable?

the execution of the following code will generate numbers from 1 through 10, instead of a serial of 1, why?

1
2
3
4
5
6
7
8
9
size_t count_calls() {
    static size_t ctr=0;
    return ++ctr;
}

int main() {
    for(size_t i=0; i!= 10; ++i)
        cout<<count_calls()<<endl;
}


Isn't this"static size_t ctr=0" executed every time? and Initialized to 0 every time? Even the memory remains but the value can be re-initialized, right?
Search for definition of keyword "static"
static is a cute keyword.

I'm not 100% sure of what I does because I only rarely use it, but when I do use it, it's when I don't want my variable to be reinitialized, and your variable indeed isn't reinitialized here. You can still use ctr = 0 in a separate statement and get your ten 1s, but like that, it will just keep on counting.

If you axe the static, then your function will print all ones.

-Albatross
Last edited on
Thanks guys, may be there are some internal mechanism to prevent a static object to be reinitialized, at least I have a clue now, thanks.
Topic archived. No new replies allowed.