0

I have a strange bug in my code:

vector<int> myVect;
for( int i =0; i< myVect.size() -1; i++)
{
    cout<< "how come I can reach this point?" << endl;
}

The ouput will be "how come I can reach this point?"

I still do not understand it. MyVect.size() is 0 as this vector is empty. Why is the condition in for loop still satisfied?

Thank you

rudky martin
  • 81
  • 1
  • 1
  • 3

3 Answers3

6

myVect.size() returns an unsigned integer. Since the vector is empty it will be 0. When you subtract 1 from that it wraps around and becomes the largest value that std::vector::size_type(generally std::size_t) can hold.

Since i which is 0 is less than that you satisfy the condition and enter the for loop.

Do note that starting in C++11 ranged based for loops were introduced. If you want to loop through a container and use its values you can use

for (const auto & e : container_name)
    // use e here in a read only manner.

If you need to modify the elements then you can use

for (auto & e : container_name)
    // use e here however you want.

This guarantees that you loop through all of the elements of the container and is generally less error prone.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
3

The return type of veccot::size() is size_t, which is an unsigned type. If you subtract from 0 (unsigned), the number is 'wrapped around' back to the maximum possible value for a size_t.

Smeeheey
  • 9,906
  • 23
  • 39
1

It is already answered that the reason you subtract 1 from unsigned 0, solution to fix your issue is to change condition to:

for( int i =0; i + 1 < myVect.size(); i++)
Slava
  • 43,454
  • 1
  • 47
  • 90