Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
138 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...