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

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

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.

这篇关于为什么在打印未初始化的变量时会看到奇怪的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)