int i的值= i ^ i;它总是为零还是未定义的行为? [英] Value of int i = i ^ i ; Is it always zero or undefined behavior?

查看:236
本文介绍了int i的值= i ^ i;它总是为零还是未定义的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下程序中,输出始终为零或未定义的行为?

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

#include<iostream>

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

使用gcc 4.8.0这个代码成功编译,输出为0.

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

推荐答案

int i= 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.

如果您在命名空间级别或已声明 i static ,则代码将很好:

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() {}


  • 或在本地定义,但 static

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


  • 这两个代码都很好,因为 存储持续时间中声明了 i 是静态地初始化的。

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

    这篇关于int i的值= i ^ i;它总是为零还是未定义的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆