Lets say that we have two compilation units as follows:
// a.cpp
extern int value2;
int value1 = value2 + 10;
// b.cpp
extern int value1;
int value2 = value1 + 10;
When I tried it on VC2010, it initializes value1
and value2
to zero first. aren't both value1
and value2
dynamically initialized and default initialization doesn't apply on them?
Thanks,
Undefined Behavior results in unpredicted behavior of the entire program. But in unspecified behavior, the program makes choice at a particular junction and continue as usual like originally function executes.
So, in C/C++ programming, undefined behavior means when the program fails to compile, or it may execute incorrectly, either crashes or generates incorrect results, or when it may fortuitously do exactly what the programmer intended.
A program can be said to contain unspecified behavior when its source code may produce an executable that exhibits different behavior when compiled on a different compiler, or on the same compiler with different settings, or indeed in different parts of the same executable.
Undefined behavior can result in a program crash or even in failures that are harder to detect and make the program look like it is working normally, such as silent loss of data and production of incorrect results.
3.6.2/1 says that "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place".
So you're right, they aren't default-initialized. But they are zero-initialized, which in fact for int
is the same thing. For a class type it's not necessarily the same thing.
That said, I'm not promising the behavior here is merely that the order of initialization is unspecified, and hence that one variable ends up as 10 and the other 20, but unspecified which is which. It might be undefined on some other grounds, but I can't think of any.
Every global variable is first zero-initialized, before every other initializations happen.
This behaviour is described under 3.6.2 [basic.start.init] / 2
:
Variables with static storage duration or thread storage duration shall be zero-initialized before any other initialization takes place.
(This is from the C++0x FDIS, but I believe the C++98 standard says the same.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With