問題描述
在下面的代碼中,變量沒有初始值并打印了這個變量.
In the following code, the variable has no initial value and printed this variable.
int var;
cout << var << endl;
輸出:2514932
double var;
cout << var << endl;
輸出:1.23769e-307
output : 1.23769e-307
我不明白這些輸出數字.誰能給我解釋一下?
I don't understand these output numbers. Can any one explain this to me?
推薦答案
簡單地說,var
沒有被初始化,讀取一個未初始化的變量會導致 未定義的行為.
Put simply, var
is not initialized and reading an uninitialized variable leads to undefined behavior.
所以不要這樣做.一旦你這樣做,你的程序就不再保證按你說的做.
So don't do it. The moment you do, your program is no longer guaranteed to do anything you say.
正式地,讀取"一個值意味著對其執行左值到右值的轉換.§4.1 指出...如果對象未初始化,則需要進行此轉換的程序具有未定義的行為."
Formally, "reading" a value means performing an lvalue-to-rvalue conversion on it. And §4.1 states "...if the object is uninitialized, a program that necessitates this conversion has undefined behavior."
實際上,這只是意味著該值是垃圾(畢竟,很容易看到讀取 int
,例如,只是獲取隨機位),但我們不能得出結論 這個,否則你會定義未定義的行為.
Pragmatically, that just means the value is garbage (after all, it's easy to see reading an int
, for example, just gets random bits), but we can't conclude this, or you'd be defining undefined behavior.
舉一個真實的例子,考慮:
For a real example, consider:
#include <iostream>
const char* test()
{
bool b; // uninitialized
switch (b) // undefined behavior!
{
case false:
return "false"; // garbage was zero (zero is false)
case true:
return "true"; // garbage was non-zero (non-zero is true)
default:
return "impossible"; // options are exhausted, this must be impossible...
}
}
int main()
{
std::cout << test() << std::endl;
}
天真地,人們會得出結論(通過評論中的推理)這永遠不應該打印 "impossible"
;但是對于未定義的行為,一切皆有可能.用 g++ -02
編譯它.
Na?vely, one would conclude (via the reasoning in the comments) that this should never print "impossible"
; but with undefined behavior, anything is possible. Compile it with g++ -02
.
這篇關于為什么在打印未初始化的變量時會看到奇怪的值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!