Search code examples
c++unsignedinteger-overflowarithmetic-expressions

Subtraction between signed and unsigned followed by division


The following results make me really confused:

int i1 = 20-80u;    // -60
int i2 = 20-80;     // -60
int i3 =(20-80u)/2; // 2147483618
int i4 =(20-80)/2;  // -30
int i5 =i1/2;       // -30
  1. i3 seems to be computed as (20u-80u)/2, instead of (20-80u)/2
  2. supposedly i3 is the same as i5.

Solution

  • IIRC, an arithmetic operation between signed and unsigned int will produce an unsigned result.

    Thus, 20 - 80u produces the unsigned result equivalent to -60: if unsigned int is a 32-bit type, that result is 4294967236.

    Incidentally, assigning that to i1 produces an implementation-defined result because the number is too large to fit. Getting -60 is typical, but not guaranteed.