Difference between static variable inside and outside function?

static int count; int main() { static int count; } 

Is there any difference between static variables declared inside and outside of any function?

(I mean scope and visibility )

+6
source share
3 answers

Your first count is available only in the module (the code in this file). The second count is only available in main .

+13
source

When you declare outside a method, it will be available to all functions static method written after his announcement. Although the declaration of a static variable in a method will be available only by this method.

+3
source

There is also a difference in the dynamic initialization of globals (see here ). To summarize, if you had:

 static int count = bar(); int main () { static int count = foo (); } 

The call to 'foo' will be executed when main is executed, but standard (C ++ '03) does not require a call to bar at all!

+3
source

Source: https://habr.com/ru/post/887184/


All Articles