未初始化的变量会怎样?C++

2022-01-18 00:00:00 initialization variables 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.

相关文章