1

I was solving a question when I encountered this behaviour and wasn't able to understand why it happened, any help would be appreciated.

vector<int> v1;
v1.push_back(0);
    
int no = v1.size() - 3;
// this prints output as expected  -> -2
cout << no << endl;
    
// this prints -> 18446744073709551614
cout << v1.size() - 3;

This is something about integer overflow, but I know nothing further.

9
  • 4
    If size is less than 3 you will have this problem. size_t is an unsigned number. In your case it looks like a 64 bit unsigned number.
    – drescherjm
    Commented Jul 16, 2021 at 21:32
  • 2
    this prints output as expected -> -2 this is undefined behavior. this prints -> 18446744073709551614 this is an expected well-defined behavior.
    – 3CxEZiVlQ
    Commented Jul 16, 2021 at 21:34
  • Unsigned arithmetic is modulo arithmetic. No surprise there. Signed overflow is fun though. Commented Jul 16, 2021 at 21:35
  • @S.M. the conversion is not UB, though can be value-preserving (size_t is smaller than int) or implementation defined. Commented Jul 16, 2021 at 21:39
  • Try casting v1.size() to a signed integer. The receiving variable and the 3 are signed integers; the v1.size() is unsigned. Commented Jul 16, 2021 at 21:47

1 Answer 1

0

The size of standard containers is represented as an unsigned integer (when using the default allocator such as in the example). Unsigned integer can represent only non-negative numbers.

When one operand of binary arithmetic operation (subtraction in this case) is unsigned (and at least as ranked as int) and the other is signed of same or lower rank, then the signed operand will be converted to the unsigned type. The result of the operation is that same type.

So, since the result of the operation is an unsigned integer, it cannot possibly be a negative number because those are not representable by unsigned integers. What happened is that the "correct" result of the operation was outside of representable numbers. This can happen both when the value is below representable range of values as well as above.

When "correct" result of unsigned arithmetic operation is outside representable range, the adjusted result that you get will be a representable value that is congruent with the "correct" result modulo M which is the number of representable values of the type (M == 2number of bits). In this case 18446744073709551614 is congruent with -2 modulo M.


Note that when result of signed arithmetic is outside the range of representable values, then the behaviour of the program is undefined. It is important to avoid that.

Not the answer you're looking for? Browse other questions tagged or ask your own question.