Does this code generate Undefined behavior or is it just unspecified behavior?

Suppose we have two compilation units:

// 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 first initializes value1 and value2 zero. are not both value1 and value2 dynamically initialized, and default initialization is not applied to them?

Thanks,

+6
source share
2 answers

3.6.2 / 1 says that "Objects with a static storage duration (3.7.1) must be initialized with zeros (8.5) before any other initialization occurs."

So, you are right, they are not initialized by default. But they are zero-initialized, which is actually the same thing for int . For a class type, this is not necessarily the same thing.

However, I do not promise that the behavior here is simply that the initialization order is unspecified, and therefore one variable ends as 10, and the other 20, but not specified, which is. It may be undefined for some other reason, but I can't think of anything.

+8
source

Each global variable is first initialized to zero before any other initialization occurs.
This behavior is described in section 3.6.2 [basic.start.init] / 2 :

Variables with a static storage duration or stream storage duration must be initialized with zeros before any other initialization begins.

(This is from C ++ 0x FDIS, but I believe the C ++ 98 standard says the same thing.)

+3
source

Source: https://habr.com/ru/post/887986/


All Articles