未初始化的变量会发生什么?C++

What happens to uninitialized variables? C++(未初始化的变量会发生什么?C++)
本文介绍了未初始化的变量会发生什么?C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

int main()
{    
    int a;
    cout << a;
    return 0;
}

我想知道为什么输出值 0.我想如果一个变量未初始化,它会输出一个垃圾值.

I am wondering why the value 0 is being output. I thought if a variable is uninitialized, it would output a garbage value.

不过,我也记得听说一个整数的默认值是0,所以我有点困惑.

However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.

谢谢

推荐答案

C++ 中未初始化的函数作用域(即本地)整数的默认行为是 不确定,这很好;然而如果在定义之前使用该值会引入未定义的行为,并且任何事情都可能发生 - 恶魔可能会从你的鼻子里飞出来.

The default behavior of an uninitialized function scope (i.e., local) integer in C++ is for it to be indeterminate, which is fine; however if that value is used before it is defined it introduces undefined behavior, and anything could happen - demons could fly out of your nose.

cppreference 上的此页面提供了默认整数行为的示例.

This page on cppreference provides examples of default integer behavior.

另一方面,所有非局部、线程局部变量,而不仅仅是整数,都是 零初始化.但是这个案例没有包含在你原来的例子中.

On the other hand, all non-local, thread-local variables, not just integers, are zero initialized. But this case wasn't included in your original example.

(旁注:通常认为简单地初始化变量并完全避免潜在危险是一种很好的做法......特别是在 全局变量.)

(Side note: It is generally considered good practice to simply initialize variables anyway and avoid potential hazards altogether... Especially in the form of global variables. )

在极少数特殊情况下(例如某些嵌入式系统)使用全局变量的最佳实践有例外;根据启动时或初始循环迭代期间的传感器读数初始化值......并且需要在循环范围结束后保留一个值.

There are exceptions to best practice using global variables in rare special cases, such as some embedded systems; which initialize values based off of sensor readings on startup, or during their initial loop iteration... And need to retain a value after the scope of their loop ends.

这篇关于未初始化的变量会发生什么?C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

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?(参数包必须位于参数列表的末尾...何时以及为什么?)