请考虑以下代码:
#include <string>
#include <iostream>
int f(int n)
{
int i = 0;
for (i = 0; n < 0 || n > 0; n *= 2, ++i) {
std::cout << "n = " << n << std::endl;
}
return i;
}
int main(int argc, char* argv[])
{
return f(argc > 1 ? std::stol(argv[1]) : 1) != 0;
}
在clang ++上输出:
n = 1
n = 2
n = 4
n = 8
n = 16
n = 32
n = 64
n = 128
n = 256
n = 512
n = 1024
n = 2048
n = 4096
n = 8192
n = 16384
n = 32768
n = 65536
n = 131072
n = 262144
n = 524288
n = 1048576
n = 2097152
n = 4194304
n = 8388608
n = 16777216
n = 33554432
n = 67108864
n = 134217728
n = 268435456
n = 536870912
n = 1073741824
n = -2147483648
n = 0
在g ++ 5和g ++ 6上输出:
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
n = 0
...
这是......一个有趣的行为。怎么了?它是编译器错误吗?
答案 0 :(得分:1)
除非使用参数0
调用程序,否则将使用非零参数调用函数f
。
循环迭代步骤n *= 2
最终将导致整数溢出,即undefined behaviour。这是程序中的错误,而不是编译器中的错误。