3
剛纔我有以下種類的錯誤:編譯時初始化C++與本身是常量變量
#include <iostream>
const int i = i;
int main(void)
{
/* not allowed by default, but with -fpermissive */
//const int i;
/* allowed by default, even without -fpermissive. Seems to initialize to 0 */
for (int j = 0; j < i; ++j)
std::cout << "hi";
/* i = 0 */
}
:
g++ const-init.cpp -Wall -Wextra -pedantic -O2
因爲編譯器默默初始化我到0某些迴路被優化掉。錯誤是由於複製粘貼錯誤而發生的。
這個'功能'有效和/或記錄在某處?它甚至有什麼好處?它有名字嗎?
編輯:沒有-02 G ++的行爲就像我希望它的行爲:它使用-O2
標誌時,將發出以下錯誤
const-init.cpp:8:19: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
const int i = i;
^
那麼,爲什麼編譯器爲我以爲0,甚至刪除整個因爲這個假設循環?
可能的重複:https://stackoverflow.com/questions/28152298/why-is-initialization-of-a-new-variable-by-itself-valid –
有可能比你需要更多的信息[本問答](http://stackoverflow.com/questions/23415661/has-c-standard-changed-with-respect-to-the-use-of-indeterminate-values-and-und),但TL; DR:don'不依賴於'我'的價值。變量'i'在它自己的初始化範圍內,但它的值沒有明確定義。 – chris
你們很快,發佈這個問題後,我注意到 - 牆確實發出了警告,但使用-O2時並不如此。我在問題中指定了 – mxmlnkn