[英]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. 用gcc 4.8.0这段代码编译成功,输出为0。
int i= i ^ i ;
Since i
is an automatic variable (ie it is declared in automatic storage duration), it is not (statically) initialized yet you're reading its value to initialize it (dynamically). 由于
i
是一个自动变量(即它在自动存储持续时间内声明),它不会 (静态)初始化,但你正在读取它的值来初始化它(动态)。 So your code invokes undefined behaviour. 所以你的代码会调用未定义的行为。
Had you declared i
at namespace level or as static
, then your code would be fine: 如果你在命名空间级别或
static
声明i
,那么你的代码就可以了:
Namespace level 命名空间级别
int i = i ^ i; //declared at namespace level (static storage duration) int main() {}
Or define locally but as static
: 或者在本地定义但是
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. 这两个代码都很好,因为
i
是静态初始化的,因为它是在静态存储持续时间内声明的。
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.
在某些体系结构(特别是Itanium)上,当您尝试使用它时,未初始化的垃圾实际上会导致崩溃。 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.
请参阅http://blogs.msdn.com/b/oldnewthing/archive/2004/01/19/60162.aspx ,了解IA64的Not Thing如何搞砸你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.