問題描述
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.
不過,我也記得聽說一個整數(shù)的默認(rèn)值是0,所以我有點困惑.
However, I also remember hearing that the default value of an integer is 0 so I am a bit confused.
謝謝
推薦答案
C++ 中未初始化的函數(shù)作用域(即本地)整數(shù)的默認(rèn)行為是 不確定,這很好;然而如果在定義之前使用該值會引入未定義的行為,并且任何事情都可能發(fā)生 - 惡魔可能會從你的鼻子里飛出來.
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 上的此頁面提供了默認(rèn)整數(shù)行為的示例.
This page on cppreference provides examples of default integer behavior.
另一方面,所有非局部、線程局部變量,而不僅僅是整數(shù),都是 零初始化.但是這個案例沒有包含在你原來的例子中.
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.
(旁注:通常認(rèn)為簡單地初始化變量并完全避免潛在危險是一種很好的做法......特別是在 全局變量.)
(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. )
在極少數(shù)特殊情況下(例如某些嵌入式系統(tǒng))使用全局變量的最佳實踐有例外;根據(jù)啟動時或初始循環(huán)迭代期間的傳感器讀數(shù)初始化值......并且需要在循環(huán)范圍結(jié)束后保留??一個值.
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.
這篇關(guān)于未初始化的變量會發(fā)生什么?C++的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!