C++ can not calculate a formula with a vector's size in it?

  • A+
int main() {     vector<int> v;     if (0 < v.size() - 1) {         printf("true");     } else {         printf("false");     } } 

It prints true which indicates 0 < -1


std::vector::size() returns an unsigned integer. If it is 0 and you subtract 1, it underflows and becomes a huge value (specifically std::numeric_limits<std::vector::size_type>::max()). The comparison works fine, but the subtraction produces a value you did not expect.

For more about unsigned underflow (and overflow), see: C++ underflow and overflow

The simplest fix for your code is probably if (1 < v.size()).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: