My question is whether the behavior of the program is defined or undefined if it's valid at all. If it's defined, is the value of x known in main?
This code is definitely not clean, but to me it should work predictably.
int x
puts the variable into the data segment which is defined to be zero at the program start. Before main()
, static initializers are called. For x
that is the code x = x + 1
. x = 0 + 1 = 1
. Thus the main() would return 1.
The code would definitely work in unpredictable fashion if x
is a local variable, allocated on stack. State of stack, unlike the data segment, is pretty much guaranteed to contain undefined garbage.