In close to the metal languages like C, C++ and D, what's the most efficient reasonably portable way (i.e. w/o using assembler, though you may assume two's complement arithmetic and wrap-around behavior) to detect overflow of an unsigned 64-bit integer on multiplication?
-
Wrap-around behaviour for unsigned types is fully specified for C and C++, and two's complement is irrelevant for such types. – caf Jul 11 '10 at 23:21
-
@Mark: C99 is fine. I mostly am interested in D, but I put C and C++ in the question because any answer for them likely applies to D as well. – dsimcha Jul 11 '10 at 23:58
-
@dscimcha: If you had made it explicit that you wanted answers for D, and not just for any C-like language you a) would have gotten answers that you can use and b) your question wouldn't have been closed as a duplicate. – Mark Byers Jul 11 '10 at 23:59
-
@Mark: I figured it made more sense not to turn away C/C++ answers because C and C++ are much more popular than D, and are very similar in terms of low level stuff like integers. – dsimcha Jul 12 '10 at 00:04
3 Answers
You can detect overflow in advance by dividing the maximum value representable by the unsigned type by one of the multiplicands; if the result is less than the other multiplicand, then multiplying them would result in a value exceeding the range of the unsigned type.
For example, in C++ (using the C++0x exact-width numeric types):
std::uint64_t left = 12;
std::uint64_t right = 42;
if (left != 0 && (std::numeric_limits<std::uint64_t>::max() / left) < right)
{
// multiplication would exceed range of unsigned
}
In C, you can use uint64_t
for the type and UINT64_MAX
for the maximum value. Or, if you only care that the type is at least 64 bits wide and not necessarily exactly 64 bits wide, you can use unsigned long long
and ULLONG_MAX
.

- 348,265
- 75
- 913
- 977
There are a few answers in this almost duplicate question. This answer should work in C, C++, and other similar languages:
if (b > 0 && a > 18446744073709551615 / b) {
// overflow handling
} else {
c = a * b;
}
Or this answer which performs the multiplication and then divides the result by one of the arguments to see if it equals the other:
x = a * b;
if (a != 0 && x / a != b) {
// overflow handling
}

- 1
- 1

- 811,555
- 193
- 1,581
- 1,452
-
5Instead of 18446744073709551615 I'd use the maximum value for the used type as specified by
macros (c) or std::numeric_limits::max (C++). – Matteo Italia Jul 11 '10 at 22:00
There are probably more efficient methods but this is an easy and portable way to do it:
// assume 'a' and 'b' are the operands to be multiplied
if( ( a != 0 ) && ( UINT64_MAX / a ) < b ) ) {
// overflow
}

- 106,671
- 19
- 240
- 328