Krishanu Debnath <no*@valid.addr esswrote:
Ole Nielsby wrote:
>[...]
What's the simplest/fastest way of performing a simple
operation on longs and detecting overflow?
long c = a + b; // but branch on overflow
if (b <= LONG_MAX - a) {c = a + b;} else {/*Overflow*/}
TODO: a and b are both negative.
That's the problem. It would take several conditional jumps
to test using nothing but longs, and conditional jumps are
bad for performance.
>One way is to perform the operation with long long:
long long temp = (long long)a + b;
c = (long)temp;
Remember : If temp cannot be represented in long you are invoking
implementation defined behavior.
I think this doesn't matter, as long as a long is returned. If c doesn't
represent temp, the next comparison will detect it:
> if ((long long)c != temp) goto blast;
Thanks to those who suggested other solutions - but I'll stick
with the long long way for now unless something more elegant
comes up - as far as I can see, the other suggestions involve
multiple conditional jumps. I just hoped there would be an
intrinsic function or some language feature I had overlooked
(like the checked/unchecked keywords of C#) that allowed
me to get code like:
add eax, ebx
jo overflow
from the C++ compilers (assuming register variables).
It puzzles me that this trivial asm is so complicated
in C++.
Regards/Ole