Home > Software design >  Why is the for loop running infinite number of times? [duplicate]
Why is the for loop running infinite number of times? [duplicate]

Time:09-22

 vector<int> arr={-1};
for(int i=0;i<(arr.size()-2);i  )
        {
            cout<<"hey"<<endl;
        }

The size of the array is 1. So logically the control should never enter the for loop. Then why does the loop run infinite number of times?

On a side Note:  for(int i=0;i<-1;i  ) works just fine.

CodePudding user response:

In this for loop

for(int i=0;i<(arr.size()-2);i  )

the expression arr,size() - 2 has a very big unsigned integer value due to the usual arithmetic conversions because the type of the expression arr.size() is an unsigned integer type.

Here is a demonstrative program.

#include <iostream>
#include <vector>

int main() 
{
    std::vector<int> v;
    
    std::cout << "v.size() = " << v.size() << '\n';
    std::cout << "v.size() - 1 = " << v.size() - 1 << '\n';
    
    return 0;
}

The program output is

v.size() = 0
v.size() - 1 = 18446744073709551615
  • Related