views:

118

answers:

1

I have one static variable declared inside a function, which is not initialized to zero explicitly.

Are all uninitialized static variables inside functions set to zero by default, just as static variables at the global (file) level are?

+4  A: 

All static variables without an explicit initializer are initialized to zero.

All the variables going into the BSS segment are initialized to zero.

In C, all global and static variables without an explicit initializer go into the BSS segment and hence are zero by default.

codaddict
Hmm.. thanks codaddict.. but while debugging i found that junk value is stored in one of the function static variable.. but it was not consistent that zero is stored in that variable and sometimes garbage is stored..
inquisitive
@inquisitive: Please show us the part of the code with this behavior.
codaddict
@inquisitive: one possibility is that some buffer overflow has trampled your function static variable. There are other possibilities, too, of course.
Jonathan Leffler
@inquisitive - did you debug an optimized build? I've been baffled by the exact same behavior while debugging a problem that occured only in release builds, only to discover that the compiler did not zero the variable until just before it was first used in the function.
Christoffer
Since the C language specification doesn't mention a *BSS*, how do you determine which variables are going into the *BSS*. What happens if I don't have a *BSS*? *(Hint: not all platforms are the same, **especially embedded platforms**)*
Thomas Matthews