Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 584
Johannes Schaub - litb Avatar asked Jul 22 '10 12:07

Johannes Schaub - litb


People also ask

How do you know if a value is initialized?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

What is an initialization and How does it differ from an assignment?

What is the difference between initialization and assignment? Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

Can reference be changed once initialized?

Once initialized, a reference cannot be changed to refer to another object.


1 Answers

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.

like image 171
Jerry Coffin Avatar answered Sep 18 '22 08:09

Jerry Coffin