3 ms·
> An expression with only one operator never overflows in a recoverable way, so it just has to be checked, not expanded (Nitpick: I think you intended to write
by Someone 5y ago
> An expression with only one operator never overflows in a recoverable way, so it just has to be checked, not expanded
(Nitpick: I think you intended to write either always or unrecoverable)
_If the target CPU doesn’t have status flags indicating overflow_, that may be more work than using a larger intermediate. For a+b, detecting overflow after the fact highly likely is faster, but already is a bit convoluted if a and b are signed and, thus, can be negative (https://stackoverflow.com/a/45261894 https://stackoverflow.com/a/45261894)
For a×b https://stackoverflow.com/questions/1815367/catch-and-compute-overflow-during-multiplication-of-two-large-integers https://stackoverflow.com/questions/1815367/catch-and-comput... has a simple algorithm, but it requires a division by b. I don’t see that perform well. Possibly, double size multiplication and then testing for overflow beats that (but, if the CPU has a ‘count leading zeroes’ instruction, I would use that (https://stackoverflow.com/a/59109502 https://stackoverflow.com/a/59109502. I haven’t checked that for correctness, but even if it can’t be made correct, it likely can provide a fast path for most multiplications that your program does)
For CPUs with an overflow bit, the compiler can use it, but not all CPUs have that.