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

后端 未结 2 472
野的像风
野的像风 2020-12-10 19:55

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

#include

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


        
2条回答
  •  鱼传尺愫
    2020-12-10 20:14

    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.

提交回复
热议问题