Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of int i = i ^ i ; Is it always zero or undefined behavior?

in following program, is output always zero, or undefined behavior?

#include<iostream>

int main()
{
    int i= i ^ i ;
    std::cout << "i = " << i << std::endl;
}

with gcc 4.8.0 this code success compiled, and output is 0.

like image 563
Khurshid Avatar asked Nov 28 '22 15:11

Khurshid


2 Answers

int i= i ^ i ;

Since i is an automatic variable (i.e it is declared in automatic storage duration), it is not (statically) initialized yet you're reading its value to initialize it (dynamically). So your code invokes undefined behaviour.

Had you declared i at namespace level or as static, then your code would be fine:

  • Namespace level

    int i = i ^ i; //declared at namespace level (static storage duration)
    
    int main() {}
    
  • Or define locally but as static:

    int main()
    {
         static int i = i ^ i; //static storage duration
    }
    

Both of these code are fine, since i is statically initialized, as it is declared in static storage duration.

like image 151
Nawaz Avatar answered Dec 06 '22 21:12

Nawaz


Undefined behavior. Uninitialized garbage doesn't actually have to be an unknown but valid value of the given type. On some architectures (specifically Itanium), uninitialized garbage can actually cause a crash when you try to do anything with it. See http://blogs.msdn.com/b/oldnewthing/archive/2004/01/19/60162.aspx for an explanation of how IA64's Not a Thing can mess you up.

like image 35
user2357112 supports Monica Avatar answered Dec 06 '22 22:12

user2357112 supports Monica