Akpr's blog

By Akpr, history, 2 years ago, In English

Dear community Why the output of below code is not -1 ?

CODE --------------------------

include<bits/stdc++.h>

using namespace std;

int main(){ vector v; cout << v.size() — 1 << endl;

}


RECIEVED OUTPUT => 4294967295 but not -1

  • Vote: I like it
  • -31
  • Vote: I do not like it

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Auto comment: topic has been updated by Akpr (previous revision, new revision, compare).

»
2 years ago, # |
  Vote: I like it +1 Vote: I do not like it

v.size() gives unsigned_int.

»
2 years ago, # |
  Vote: I like it 0 Vote: I do not like it

Because v.size() is size_t which is unsigned type (width of type is implementation-defined).
v.size() - 1 = (0 :: size_t) - (1 :: int) = [1 casting to wider type size_t] = (0 :: size_t) - (1 :: size_t) = (2^b - 1 :: size_t) [b - size of size_t in bytes].

In other words, unsigned overflow was happen.