views:

687

answers:

5

I have this question, which i thought about earlier, but figured it's not 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's valid at all. If it's defined, is the value of x known in main?

+39  A: 

I'm pretty sure it's defined, and x should have the value 1. §3.6.2/1 says: "Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place."

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

Jerry Coffin
+1 and <acc> for the strong standard's quoting answer
Johannes Schaub - litb
Hm, amazing how subtle yet important "before any other initialization takes place." is.
GMan
I wish it was undefined as then we could say don't write stuff like that its hard to work out what you mean without looking it up in the standard.
Martin York
@Martin York: I, for one, have no problem at all with saying "don't do that", about code like this (and quite a few other things that have defined behavior).
Jerry Coffin
+3  A: 

The 'x' variable in stored in the .bss, which is filled with 0s when you load the program. Consequently, the value of 'x' is 0 when the program gets loaded in memory.

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

I don't know if it's valid or not, but the behavior is not undefined.

Tomaka17
+5  A: 

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.

Dummy00001
A: 

Before the main call x must be initialized to 0 therefore it's value must be 1 one you enter main, and you will return 1. It's a defined behavior.

LostMohican
A: 

Exited: ExitFailure 1

from codepad.org

BE Student
Please comment why u said wrong....Because with out mentioning reason ..how i can came to know...?
BE Student
Probably because the question is not what a particular compiler will generate, but whether the standard guarantees that the program must be so. That is, it is not questioning whether a compiler will return 1, but whether *all* compilers are *required* to do so.
David Rodríguez - dribeas