What happens to uninitialized variables? 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++ 中未初始化函数作用域(即本地)整数的默认行为是 indeterminate,这很好;然而如果在定义之前使用该值,则会引入未定义的行为,并且任何事情都可能发生 - 恶魔会从你的鼻子里飞出来.
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++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未初始化的变量会怎样?C++
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01