One more example to show unsigned data type wraps around
instead of overflow:
unsigned int i = std::numeric_limits<unsigned int>::max(); // (say) 4294967295
Assigning a -ve
number to the unsigned
is not recommended but for the illustrative purpose, I'm using it below
unsigned int j = -1; // 4294967295 wraps around(uses modulo operation)
unsigned int j = -2; // 4294967294
Visualizing the unsigned (0 to max)
range with respect to the modulo of max+1
(where max = 2^n):
Range : 0, 1, 2,......., max-2, max-1, max
.................................................................................
Last-to-First : -(max+1), -max, -(max-1),......., -3, -2, -1
First-to-Last : max+1, max+2, max+3,......., max+max-1, max+max, max+max+1
Modulo Addition Rule: (A + B) % C = (A % C + B % C) % C
[max + max + 1] % (max + 1) = [(max) + (max + 1)] % (max + 1)
= [(max % (max + 1)) + ((max + 1) % (max + 1))] % (max + 1)
= [(max % (max + 1)) + 0] % (max + 1)
= [max] % (max + 1)
= max