-1

I had tried running this code

// vector::size
#include <iostream>
#include <vector>

int main ()
{
   std::vector<int> myints;
   std::cout << "size: " << myints.size() << '\n';
   std::cout << "size: " << myints.size()-1 << '\n';

 return 0; 
}

And Surprisingly the output came

0

garbage Value

It should be

0

-1

Here's the :code

Community
  • 1
  • 1
JVJplus
  • 77
  • 3
  • 10

1 Answers1

7

myints.size() is an unsigned type: formally a std::vector<int>::size_type. Subtracting 1 from an unsigned type with a value of 0 will cause wrap-around effects, in your case, to

std::numeric_limits<std::vector<int>::size_type>::max()

It would not have printed "garbage value": but the number above, which will be one less than a large power of 2.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470