Theory:
According to both C++98 and C++03 standards:
3.6.2 Initialization of non-local objects, §1:
Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place.
3.7.1 Static storage duration, §1:
All objects which neither have dynamic storage duration nor are local have static storage duration.
3.7.1 Static storage duration, §3:
The keyword static
can be used to declare a local variable with static storage duration.
And also 8.5 Initializers, §6:
Every object of static storage duration shall be zero-initialized at program startup before any other initialization takes place.
This is the same in both standards. The only difference is in formulation of C++98's 8.5 §6:
The memory occupied by any object of static storage duration shall be zero-initialized
at program startup before any other initialization takes place.
Example:
Here's the example, where x
and y
and have static storage duration, thus standard guarantees that both of them will be zero-initialized at program startup. Note that there are also POD objects a
and b
declared in the same manner, thus having static storage duration, which means that their members (i
and d
) will be zero-initialized as well:
struct POD {
int i;
double d;
};
int x;
POD a;
int foo() {
static int y;
return y;
}
int main() {
static POD b;
std::cout << "x = " << x << std::endl;
std::cout << "y = " << foo() << std::endl;
std::cout << "a.i = " << a.i << std::endl;
std::cout << "b.d = " << b.d << std::endl;
}
Output of this example is then of course:
x = 0
y = 0
a.i = 0
b.d = 0