Suppose I have two size_t
variables and I need to multiply them and get result as size_t
.
size_t first = ...;
size_t second = ...;
size_t result = first * second;
They might overflow so I need to check for that.
The "clean" way would be to first check that multiplication is possible using division:
if( second != 0 && first > ((size_t)-1) / second ) {
//handle overflow
}
//proceed with computing first * second
The seemingly less "clean" way is to first multiply and then check the result with division:
size_t result = first * second;
if( second != 0 && result / second != first )
//handle overflow
}
However because unsigned numbers multiplication "safely overflows" by wrapping around zero this works just fine and looks like equivalent to the former code (which first checks, then multiplies).
Are there any potential problems with the second code? Will it always be as good as the first one?