c++initializationinitialization-order

Is this self initialization valid?


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?


Solution

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