Strange loop behavior - bug?

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; // this line was added for (int n=mk; n<=l; ++n) // m+k was replaced by l { if (n<0 || n>=3) continue; ++acc; } assert (acc>0); cout << "acc: " << acc << endl; } } 

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?

+4
source share
1 answer

Your int m will be increased to unsigned int . In the first loop, this means that mk is -1 as an unsigned value, which is the maximum unsigned value and is obviously larger than m+k (when comparing n it gets boosted). To put it in perspective, you get n as an unsigned representation of -1 and m+k equal to 1. Of course, when you save -1 unsigned to a signed integer, it overflows and technically undefined behavior. It most likely retains its -1 representation, and then returns to the maximum unsigned value.

Here is a brief description of the first iteration:

Iteration 1:
m: 0
k: 1u
n = mk: -1u = max uint stored in signed int
m + k: 1u
n <= m + k → max uint <= 1u

In your second example, n does not advance compared to another signed integer and compares two significant integers. In your third, nothing is indicated.

+3
source

Source: https://habr.com/ru/post/1482576/


All Articles