我在 Windows 7 机器上使用 Visual Studio 2012,当尝试运行以下代码片段(使用 x64 模式下的默认 VC11 C++ 编译器编译)时,断言失败,这意味着永远不会进入内部循环:
void loopTest1()
{
const unsigned int k = 1;
for (int m=0; m<3; ++m)
{
int acc = 0;
for (int n=m-k; n<=m+k; ++n)
{
if (n<0 || n>=3) continue;
++acc;
}
assert (acc>0);
cout << "acc: " << acc << endl;
}
}
现在我改变内循环的结束条件:
void loopTest2()
{
const unsigned int k = 1;
for (int m=0; m<3; ++m)
{
int acc = 0;
int l = m+k; // this line was added
for (int n=m-k; n<=l; ++n) // m+k was replaced by l
{
if (n<0 || n>=3) continue;
++acc;
}
assert (acc>0);
cout << "acc: " << acc << endl;
}
}
然后我得到正确的结果:
acc: 2
acc: 3
acc: 2
当我用 const unsigned int k
硬编码的 1 替换它时,它也可以工作:
void loopTest3()
{
//const unsigned int k = 1;
for (int m=0; m<3; ++m)
{
int acc = 0;
for (int n=m-1; n<=m+1; ++n) //replaced k with 1
{
if (n<0 || n>=3) continue;
++acc;
}
assert (acc>0);
cout << "acc: " << acc << endl;
}
}
编译器是否执行了一些错误的优化?或者有什么具体原因,为什么第一种情况的行为至少是出乎意料的?