473,396 Members | 1,815 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Detecting integer overflow

Given two longs:

long a = ...;
long b = ...;

What's the simplest/fastest way of performing a simple
operation on longs and detecting overflow?

long c = a + b; // but branch on overflow

One way is to perform the operation with long long:

long long temp = (long long)a + b;
c = (long)temp;
if ((long long)c != temp) goto blast;

but it seems a bit strange that I'd have to use long long
for all computations, to deal with the relatively rare case
of overflow.
Sep 21 '06 #1
8 2379
Ole Nielsby wrote:
Given two longs:

long a = ...;
long b = ...;

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.
>
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.

Just check if temp belongs to [LONG_MIN, LONG_MAX]

Krishanu
Sep 21 '06 #2
Ole Nielsby wrote:
Given two longs:

long a = ...;
long b = ...;

What's the simplest/fastest way of performing a simple
operation on longs and detecting overflow?

long c = a + b; // but branch on overflow

One way is to perform the operation with long long:

long long temp = (long long)a + b;
c = (long)temp;
if ((long long)c != temp) goto blast;

but it seems a bit strange that I'd have to use long long
for all computations, to deal with the relatively rare case
of overflow.

Would the following work?

long c = a + b;
if (a 0 && b 0 && c < 0)
Overflow();
Sep 21 '06 #3
Ole Nielsby posted:
What's the simplest/fastest way of performing a simple
operation on longs and detecting overflow?
Off the top of my head, you could test for a negative answer where a positive
answer was expected, and vice versa -- but that's only after the overflow has
taken place. E.g.:
long a=3000000000,b=4000000000;

long c = a*b;

if(c < 0) throw Overflow();

Ofcourse, you want to make sure beforehand that overflow doesn't invoke
undefined behaviour:

COMPILE_TIME_ASSERT( std::numeric_limits<long>::modulo );

--

Frederick Gotham
Sep 21 '06 #4

Krishanu Debnath <no*@valid.addresswrote:
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
Sep 21 '06 #5
Ole Nielsby wrote:
>> 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.
So you want to branch without jumping?
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;
And this is not a conditional jump? And the extension to long long and the
comparison takes no time? Maybe your way is faster than the others
suggested, but you can't know for sure.

--
Salu2
Sep 21 '06 #6
Julián Albo <JU********@terra.eswrote:
And this is not a conditional jump?
I was just pointing out that my solution has fewer conditional
jumps than the others.
And the extension to long long and the comparison takes no
time?
Generally, such operations are a lot faster than conditional
jumps because they are predictable and don't mess up the
instruction pipelines the way conditional jumps do.
Maybe your way is faster than the others suggested, but you
can't know for sure.
Naturally, testing will be required to make the best decision.
BTW, the outcome is likely to depend much on the CPU type
- I guess the "long long" solution will be the fastest on 64 bit
architectures that can handle long long natively, while the
others might be faster on 32 bit CPUs, depending on how
the compiler implements the long long comparison.

Regards/Ole N.
Sep 22 '06 #7
Ole Nielsby wrote:
>And this is not a conditional jump?
I was just pointing out that my solution has fewer conditional
jumps than the others.
>And the extension to long long and the comparison takes no
time?
Generally, such operations are a lot faster than conditional
jumps because they are predictable and don't mess up the
instruction pipelines the way conditional jumps do.
But you are no choosing between a way without jumps and one with jumps, just
between more or less jumps. It's no so easy to predict the
predictability ;)

--
Salu2
Sep 22 '06 #8
An easier test than true overflow is whether your int
(let's say it's 32 bits) has exceeded half its range,
either in the positive or negative direction:

int overflow = 1 & ((x>>30) ^ (x>>31));

Think of it as an overflow of a 31 bit integer. In
many algorithms if the magnitude of the value has become this
large, it will truly overflow soon.

Steve
Sep 22 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Karthik | last post by:
Hi, I am writing this application that needs a lot of arithmetic calculations. I was wondering if C++ language specifies any way of detecting arithmetic overflows. Let us consider the following...
2
by: Paul Emmons | last post by:
Can anyone suggest example code, or how to proceed, in adding or subtracting two long long integers (I'm working in gcc with Linux, where a long long is 64 bits) and determining whether an overflow...
2
by: alok | last post by:
I am getting inconsistent behvior on Linux and Solaris platfors while computing doule ( 64 bit precision ) multiplications. I have following two double numbers whose integer representation is as...
7
by: wij | last post by:
Hi: Is there better way of detecting multiplication overflow for type long than by using double precision of lldiv to verify the result? Thanks in advance. I.J.Wang
25
by: junky_fellow | last post by:
Is there any way by which the overflow during addition of two integers may be detected ? eg. suppose we have three unsigned integers, a ,b, c. we are doing a check like if ((a +b) > c) do...
7
by: pocmatos | last post by:
Hi all, What the best way to detect under/over flow in a program with a lot of computations? For example: #include <iostream> #include <limits> using namespace std;
6
by: Andre Majorel | last post by:
How do you compute an off_t with overflow detection ? Ideally, the target language is C89/C90 and the target platform is reasonably recent versions of the major Unixen. If there is no practical...
42
by: thomas.mertes | last post by:
Is it possible to use some C or compiler extension to catch integer overflow? The situation is as follows: I use C as target language for compiled Seed7 programs. For integer computions the C...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.