0

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
  • 97
  • 1
  • 3
  • 11
  • Look at the type. – chris Feb 06 '18 at 15:30
  • 7
    I seriously doubt that your program literally output "garbage Value". – molbdnilo Feb 06 '18 at 15:30
  • 1
    It should not be. It's an unsigned type, there are no negative values. – Justin Randall Feb 06 '18 at 15:32
  • @molbdnilo: That's a good question. I need to check but I *think* the behaviour of `cout` is implementation defined for `unsigned` types over a certain size. Seems that theoretically, "garbage Value" is allowed by the standard. – Bathsheba Feb 06 '18 at 15:37
  • @Bathsheba, As far as I can tell from `operator<<` and `num_put::do_put`, an `unsigned long long` with default other settings will be output the same way as a call to `printf("%ull", val)`, and likewise for other fundamental unsigned types. I'm not so sure you'd have a potential problem from `size_t`, given that it would either fit an overload or cause an ambiguity. – chris Feb 06 '18 at 16:16

1 Answers1

8

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
  • 231,907
  • 34
  • 361
  • 483