What will the unsigned int
contain when I overflow it? To be specific, I want to do a multiplication with two unsigned int
s: what will be in the
It probably depends a bit on your compiler. I had errors like this years ago, and sometimes you would get runtime error, other times it would basically "wrap" back to a really small number that would result from chopping off the highest level bits and leaving the remainder, i.e if it's a 32 bit unsigned int, and the result of your multiplication would be a 34 bit number, it would chop off the high order 2 bits and give you the remainder. You would probably have to try it on your compiler to see exactly what you get, which may not be the same thing you would get with a different compiler, especially if the overflow happens in the middle of an expression where the end result is within the range of an unsigned int.
unsigned
numbers can't overflow, but instead wrap around using the properties of modulo.
For instance, when unsigned int
is 32 bits, the result would be: (a * b) mod 2^32
.
As CharlesBailey pointed out, 253473829*13482018273
may use signed multiplication before being converted, and so you should be explicit about unsigned
before the multiplication:
unsigned int someint = 253473829U * 13482018273U;
Unsigned integer overflow, unlike its signed counterpart, exhibits well-defined behaviour.
Values basically "wrap" around. It's safe and commonly used for counting down, or hashing/mod functions.