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++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
