Does this code produce Undefined Behavior or it is merely Unspecified Behavior?
S

2

6

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,

Shanly answered 13/5, 2011 at 2:28 Comment(0)
C
8

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.

Canon answered 13/5, 2011 at 2:33 Comment(0)
C
3

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.)

Creditable answered 13/5, 2011 at 2:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.