I work with Visual Studio 2012 on a computer running Windows 7 and when I try to execute the following code fragment (compiled using the VC11 C ++ compiler by default in x64 mode) the statement fails, which means that the inner loop will never be entered:
void loopTest1() { const unsigned int k = 1; for (int m=0; m<3; ++m) { int acc = 0; for (int n=mk; n<=m+k; ++n) { if (n<0 || n>=3) continue; ++acc; } assert (acc>0); cout << "acc: " << acc << endl; } }
Now I change the condition for the end of the inner loop:
void loopTest2() { const unsigned int k = 1; for (int m=0; m<3; ++m) { int acc = 0; int l = m+k;
Then I get the correct result:
acc: 2 acc: 3 acc: 2
When I replace const unsigned int k with hard-coded 1, it works too:
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; } }
Does the compiler perform some false optimizations? Or is there any specific reason why the behavior in the first case is at least unexpected?
source share