我正在使用Windows 7机器上的Visual Studio 2012,在尝试运行以下代码片段时(使用默认的VC11 C ++编译器以x64模式编译),断言失败,这意味着内部循环从未执行:
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;
}
}
编译器是否进行了一些错误的优化? 或者有没有特定的原因,导致第一种情况的行为至少是出人意料的?
int k = 1
进行了测试,它起作用了!你能否把你的评论转化成一篇回答? - Ben