用自身初始化 C++ const 变量
Initialize C++ const variable with itself
刚才我遇到了以下类型的错误:
#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
因为编译器默默地将 i 初始化为 0,一些循环被优化掉了。发生错误是因为复制粘贴错误。
这个 'feature' 有效 and/or 是否记录在某处?它有什么用?它有名字吗?
编辑:没有 -O2 g++ 的行为就像我希望它的行为一样:它发出以下错误
const-init.cpp:8:19: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
const int i = i;
^
那么,为什么编译器在使用 -O2
标志时假设 i 为 0,甚至因为这个假设而删除整个循环?
它的名字是 "undefined behaviour",将 i
设置为 0 只是一种可能的结果。
刚才我遇到了以下类型的错误:
#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
因为编译器默默地将 i 初始化为 0,一些循环被优化掉了。发生错误是因为复制粘贴错误。
这个 'feature' 有效 and/or 是否记录在某处?它有什么用?它有名字吗?
编辑:没有 -O2 g++ 的行为就像我希望它的行为一样:它发出以下错误
const-init.cpp:8:19: warning: ‘i’ is used uninitialized in this function [-Wuninitialized]
const int i = i;
^
那么,为什么编译器在使用 -O2
标志时假设 i 为 0,甚至因为这个假设而删除整个循环?
它的名字是 "undefined behaviour",将 i
设置为 0 只是一种可能的结果。