Q about static int

Could anyone explain to me why, each time GenerateID() is called, it doesn't re-initialize s_nID back to 0?

Thanks! ..........D

1
2
3
4
5
6
7
8
9
10
11
12
13
int GenerateID()
{
    static int s_nID = 0;
    return s_nID++;
}
 
int main()
{
    std::cout << GenerateID() << std::endl;
    std::cout << GenerateID() << std::endl;
    std::cout << GenerateID() << std::endl;
    return 0;
}

This program prints:

0
1
2
Last edited on
closed account (Eybjz8AR)
...
Last edited on
@wtlyons: What are you talking about? The variable definitely does need to be static.

@Dazzer: Static variable initializations are only executed once, the first time they are run. After the first run, they are skipped.
Thanks firedraco, now i get it!
Topic archived. No new replies allowed.