Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,

like image 614
Khaled Alshaya Avatar asked May 13 '11 02:05

Khaled Alshaya


People also ask

Is unspecified behavior undefined behavior?

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.

What is undefined behavior in programming?

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.

What does the term unspecified behavior mean?

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.

What happens undefined behavior?

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.


2 Answers

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.

like image 170
Steve Jessop Avatar answered Sep 30 '22 13:09

Steve Jessop


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

like image 40
Xeo Avatar answered Sep 30 '22 12:09

Xeo