user1086635
user1086635

Reputation: 1544

Initializing object with indeterminate value

Does the following invoke undefined behavior?

int x;
int i = x;

Reference from C++03

(4.1/1) If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

Edit: However, from (3.3.1/1) an object may be initialized with its own indetermine value, why is that? i.e.

int x = x; //not an undefined behaviour

Upvotes: 2

Views: 223

Answers (5)

Pubby
Pubby

Reputation: 53097

It's undefined if x is uninitialized, as said in your quote.

int x; // 0 initialized
int i = x;

int main() {
  int z; // not initialized
  int k = z; // UB
}

Upvotes: 1

curiousguy
curiousguy

Reputation: 8318

int x = x; //not an undefined behaviour

Wrong.

Upvotes: -1

Jesse Good
Jesse Good

Reputation: 52395

The only thing to remember is that this is okay:

static int x;
int j = x;

but your example is not.

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75150

Yes, because you're reading the value of a variable (x) which was uninitialised and unassigned.

Upvotes: 6

Alturis
Alturis

Reputation: 74

It invokes perfectly defined behavior. Whatever garbage value x was when it is allocated on the stack will be assigned to i as is.

Depending on your compiler, however, you may get a compile time warning about referencing an uninitialized variable.

Upvotes: -1

Related Questions