5

Possible Duplicate:
Does gcc automatically initialize static variables to zero?

Are statically declared objects inside a function guaranteed to be initialized with 0?

For example:

int func(void)
{
   static int x;
   ...
}

Does the standard promise that x = 0 upon the first invocation of func()?

Community
  • 1
  • 1
Mark
  • 6,052
  • 8
  • 61
  • 129

5 Answers5

5

The C99 Standard says:

5.1.2 Execution environments

... All objects in static storage shall be initialized (set to their initial values) before program startup.

And it also says that a local variable defined with static qualifier has "static storage" and that in the absence of an initialization all objects take the value 0 of the right type for them.

pmg
  • 106,608
  • 13
  • 126
  • 198
1

Short answer, yes.

Static, uninitialised variables reside in the .bss segment of the executable and the operating system allocates and zeroes them on program startup, before main is invoked.

Blagovest Buyukliev
  • 42,498
  • 14
  • 94
  • 130
  • 1
    It is still a good idea to initialize it. – Dima May 04 '11 at 17:49
  • 1
    It is a good practice, IMHO. This way you never have to think about which variables are initialized automatically and which are not. Let's say you later decide that `x` should not be static, but forget to initialize it, and that bug will be a royal pain to find. – Dima May 04 '11 at 17:58
  • 1
    It is **not** "a good idea" to initialize it explicitly. For various reasons, almost all compilers will put explicitly-initialized variables in `.data` rather than `.bss` (or equivalents), enlarging your binary for **no purpose**. This can make a big difference with large arrays or structures. – R.. GitHub STOP HELPING ICE May 04 '11 at 19:49
1

That's right. For more insight you can refer to exact same question asked a while ago here:

Does gcc automatically initialize static variables to zero?

Community
  • 1
  • 1
asami
  • 773
  • 6
  • 12
0

Yes, it does get initialized to zero. But, however, it might be still not a great idea to use static method variables at all. C# has explicitly avoided the confusion, and have dropped support for static method variables.

http://blogs.msdn.com/b/csharpfaq/archive/2004/05/11/why-doesn-t-c-support-static-method-variables.aspx

kuriouscoder
  • 5,394
  • 7
  • 26
  • 40
0

All static variables are stored in Datasection in the memory section, where all the variables are set to default values.

maheshgupta024
  • 7,657
  • 3
  • 20
  • 18