473,668 Members | 2,552 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2394
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_AS SERT( std::numeric_li mits<long>::mod ulo );

--

Frederick Gotham
Sep 21 '06 #4

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
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********@ter ra.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
2743
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 program. #include <iostream> using namespace std;
2
6063
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 or underflow occurs, invalidating the result? I have written a solution in assembler. It's simple, thanks to the overflow flag. But without access to this part of the hardware in the C language, how would one do it? Thank you for your...
2
3737
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 following I have a union typedef union { double double_val; unsigned long long uint_val;
7
2417
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
6247
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 something;
7
2206
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
3800
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 way to do that without limiting the target platform set to FreeBSD + Linux + NetBSD + OpenBSD or adding the requirement of conformance to some combination of SUS v2, SUS v3 and C99, I'll settle for that. Overflow-safe versions of + and * would...
42
7004
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 type 'long' is used. That way native C speed can be reached. Now I want to experiment with raising a Seed7 exception (which is emulated with setjmp(), longjmp() in C) for integer
0
8459
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8889
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8790
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8570
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8650
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4202
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2781
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1779
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.