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

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

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.

相关文章