Why do I see strange values when I print uninitialized variables?(为什么在打印未初始化的变量时会看到奇怪的值?)
问题描述
在下面的代码中,变量没有初始值并打印了这个变量.
In the following code, the variable has no initial value and printed this variable.
int var;
cout << var << endl;
输出:2514932
double var;
cout << var << endl;
输出:1.23769e-307
output : 1.23769e-307
我不明白这些输出数字.谁能给我解释一下?
I don't understand these output numbers. Can any one explain this to me?
推荐答案
简单地说,var
没有被初始化,读取一个未初始化的变量会导致 未定义的行为.
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.
正式地,读取"一个值意味着对其执行左值到右值的转换.§4.1 指出...如果对象未初始化,则需要进行此转换的程序具有未定义的行为."
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."
实际上,这只是意味着该值是垃圾(毕竟,很容易看到读取 int
,例如,只是获取随机位),但我们不能得出结论 这个,否则你会定义未定义的行为.
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;
}
天真地,人们会得出结论(通过评论中的推理)这永远不应该打印 "impossible"
;但是对于未定义的行为,一切皆有可能.用 g++ -02
编译它.
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
.
这篇关于为什么在打印未初始化的变量时会看到奇怪的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在打印未初始化的变量时会看到奇怪的值


基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01