为什么当我打印未初始化的变量时,我看到奇怪的值? [英] Why do I see strange values when I print uninitialized variables?
问题描述
以下,代码中的变量没有初始值并打印此变量。
cout<< var< endl;
输出:2514932
double var;
cout<< var< endl;
输出:1.23769e-307
我不明白这个数量的输出。可以有人解释我吗?
简单地说, var
初始化并读取未初始化的变量可导致 未定义的行为 。
所以不要这样做。
正式地,读取一个值意味着对其执行左值到右值转换。并且§4.1说明...如果对象未初始化,则需要此转换的程序具有未定义的行为。
务实地,这意味着该值是垃圾毕竟,很容易看到读取 int
,例如,只是得到随机位),但我们不能结束这个,或者你
<$ c $ c> #include< iostream>
const char * test()
{
bool b; // uninitialized
switch(b)//未定义的行为!
{
case false:
returnfalse; // garbage is zero(zero is false)
case true:
returntrue; // garbage is non-zero(non-zero is true)
默认值:
returnimpossible; // options are exhausted,这一定是不可能的...
}
}
int main()
{
std :: cout< < test()<< std :: endl;
}
Naïvely,通过评论中的推理,从不打印impossible
;但是具有未定义的行为,任何事情都是可能的。使用 g ++ -02
编译它。
following, variable in code has no initial value and printed this variable.
int var;
cout << var << endl;
output : 2514932
double var;
cout << var << endl;
output : 1.23769e-307
i don't understand this numbers of output. Can any one explain me?
Put simply, var
is not initialized and reading an uninitialized variable leads to undefined behavior.
So don't do it. The moment you do, your program is no longer guaranteed to do anything you say.
Formally, "reading" a value means performing an lvalue-to-rvalue conversion on it. And §4.1 states "...if the object is uninitialized, a program that necessitates this conversion has undefined behavior."
Pragmatically, that just means the value is garbage (after all, it's easy to see reading an int
, for example, just gets random bits), but we can't conclude this, or you'd be defining undefined behavior.
For a real example, consider:
#include <iostream>
const char* test()
{
bool b; // uninitialized
switch (b) // undefined behavior!
{
case false:
return "false"; // garbage was zero (zero is false)
case true:
return "true"; // garbage was non-zero (non-zero is true)
default:
return "impossible"; // options are exhausted, this must be impossible...
}
}
int main()
{
std::cout << test() << std::endl;
}
Naïvely, one would conclude (via the reasoning in the comments) that this should never print "impossible"
; but with undefined behavior, anything is possible. Compile it with g++ -02
.
这篇关于为什么当我打印未初始化的变量时,我看到奇怪的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!