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 unsigned int
after the multiplication is finished?
unsigned int someint = 253473829*13482018273;
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 unsigned int
after the multiplication is finished?
unsigned int someint = 253473829*13482018273;
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;
253473829*13482018273
may use signed integer arithmetic which may overflow before the result is converted to unsigned int
. –
Obsessive unsigned int
s, even if the example code shows something else. –
Nelle 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.
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.
© 2022 - 2024 — McMap. All rights reserved.
UINT_MAX + 5
rolls over and becomes 4. – Choong