0

I am trying to run a loop on vector but not on the last two elements. So for that I used the following implementation:

vector<int> x;
for(int i=0;i<x.size()-2;i++){
    cout<<"looping over element"<<endl;
}

However, running the above code with no elements inserted into x leads to an infinite loop. Ideone link:

Why do I get this behavior? If x.size()==0 then i<-2 condition should not hold and the code should never enter the for loop

dwadwge
  • 13
  • 1

2 Answers2

4

x.size() returns an unsigned value. If this is smaller than 2 then the value will underflow and the result will become very large.

On the other hand since i is a signed type hen it will sooner or later come to the max value of an int (which will still be less than the result of x.size() - 2), and then i++ will lead to arithmetic overflow which is undefined behavior.

Before you attempt this loop you must make sure that x.size() >= 2, and you need to make sure that the counter variable is an unsigned type (like size_t):

if (x.size() >= 2)
{
    for (size_t i = 0; i < x.size() - 2; ++i)
    {
        // ...
    }

}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

When x.size() is smaller than 2, and you subtract two, you get some big value, as the result is unsigned, and ((someunsigned)-1) is a huge number So the loop runs:

i=0
i=50000
i=1000000
i=4,294,967,295 //Stop

So, you have no infinite loop, only a very long running loop

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29