为什么在打印未初始化的变量时会看到奇怪的值?

时间:2023-03-09
本文介绍了为什么在打印未初始化的变量时会看到奇怪的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在下面的代码中,变量没有初始值并打印了这个变量.

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 编译它.

Navely, 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和c++上下文中静态、自动、全局和局部变量的区别

相关文章