0

Demo Code: This is the driver code

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int main()
{
    vector<int> v1={} ;
    cout<<v1.size()-1;
}

Output: Upon execution

18446744073709551615

EDIT

We can simply use static_cast<int>(v1.size()-1) to rule out unsigned behaviour and overflow.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
  • 2
    18446744073709551615 is positive – Thomas Sablik Jun 23 '20 at 16:37
  • 3
    Yes this is obvious to some folk, but do note the question is well-asked, with compilable code and behaviour documented. It's difficult to search for a duplicate on this if you don't already know the answer. – Bathsheba Jun 23 '20 at 16:42
  • 1
    @Bathsheba FWIW, if you google *vector size minus 1 garbage c++* the dupe target is the very first result in google. To me that's not too difficult of a search to come up with. – NathanOliver Jun 23 '20 at 16:47
  • @NathanOliver True and you found an excellent duplicate (I think you should be able to upvote the dupe spotter for +2, but that’s another matter of course.) – Bathsheba Jun 23 '20 at 17:27
  • "We can simply [cast to `int`] to rule out unsigned behaviour and overflow" No, you can't! You cast the result of the subtraction to `int`. So, you cast `0u - 1` to `int` and just so happen to get the implementation-defined result that `0u - 1` means the max unsigned value, i.e. an all-`1` unsigned bit pattern, which also means signed `-1` on your system. That doesn't prove anything. – underscore_d Jun 26 '20 at 11:17
  • @underscore_d: have you ever in your life seen a C++-capable computer that treats an all-`1` bit pattern as something other than `-1`? Because I haven't. – TonyK Jun 26 '20 at 11:24
  • @TonyK No, but (until C++20, which mandates two's complement) the language doesn't require that, and that IMO is worth pointing out. I don't like relying on implementation-defined behaviour, even if all extant implementations define it the same way. :-) – underscore_d Jun 26 '20 at 11:26

0 Answers0