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
.
这篇关于为什么在打印未初始化的变量时会看到奇怪的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在打印未初始化的变量时会看到奇怪的值
基础教程推荐
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01