Is this initialization valid?

I have this question that I thought about before, but decided it wasn’t trivial to answer

int x = x + 1; int main() { return x; } 

My question is whether the behavior of the program is defined or undefined, if it really is at all. If defined, is the value of x known in main ?

+63
c ++ initialization
Jul 22. 2018-10-22T00:
source share
4 answers

I am sure that it is defined, and x should have the value 1. §3.6.2 / 1 says: "Objects with a static storage duration (3.7.1) must be initialized with zeros (8.5) before any other initialization takes place."

After that, I think it's all pretty simple.

+98
Jul 22 2018-10-22T00:
source share

My question is whether the behavior of the program is defined or undefined, if it really is at all. If defined, is the value of x known mainly?

This code is definitely not clean, but for me it should work predictably.

int x places the variable in the data segment, which is defined as zero when the program starts. Before main() , static initializers are called. For x this is the code x = x + 1 . x = 0 + 1 = 1 . So main () will return 1.

The code definitely works in an unpredictable way if x is a local variable allocated on the stack. The state of the stack, unlike the data segment, is pretty much guaranteed to contain undefined garbage.

+11
Jul 22 '10 at 13:12
source share

The variable 'x' is stored in .bss, which is populated with 0s when the program loads. Therefore, the value of "x" is 0 when the program is loaded into memory.

Then, before calling main, "x = x + 1" is executed.

I don’t know if this is true or not, but the behavior is not undefined.

+6
Jul 22 '10 at 13:10
source share

Before the main call, x must be initialized to 0, so the value must be 1, which you enter main, and you will return 1. This is a specific behavior.

0
Jul 22 2018-10-22T00:
source share



All Articles