0

I'm learning the modifiers of variable in C++. I see this code in the tutorial:

int func()
{
    static int number = 1;
    return ++number;
}

int main()
{
    int i = func();
    printf("i is %d", i); //This gives 2
    i = func();
    printf("i is %d", i); //This gives 3
    return 0;
}

From my understanding, I think the first time func() is called, it defines the variable in the global space. However, the next time func() is called, it will try to do the same thing in the global space, but why it doesn't result in a redefinition error?

  • @S.M. Sorry but I'm a little confused. Since from what I learned, static means the variable has the same duration as the program. So the conflict is still there? – Gaaaavin Sep 01 '21 at 01:05
  • [Static local variables](https://en.cppreference.com/w/cpp/language/storage_duration#Static_local_variables) are special. Such a variable is initialized exactly once, when execution passes over its definition for the first time. – Igor Tandetnik Sep 01 '21 at 01:08
  • 1
    *However, the next time func() is called, it will try to do the same thing in the global space...* Nope, the next time it re-uses the first one which has maintained its state from the prior call. – Eljay Sep 01 '21 at 01:08
  • @IgorTandetnik This answers my question. Thank you so much! – Gaaaavin Sep 01 '21 at 01:13
  • It's much better to get some textbooks, not online tutorials. – prehistoricpenguin Sep 01 '21 at 01:54
  • Does this answer your question? [What is the lifetime of a static variable in a C++ function?](https://stackoverflow.com/questions/246564/what-is-the-lifetime-of-a-static-variable-in-a-c-function) – prehistoricpenguin Sep 01 '21 at 01:55

0 Answers0