473,569 Members | 2,542 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to judge overflow of sum of two operands?

Given: signed a, b;
How to judge overflow of the sum of these two operands? Just use one
*if* statement.

Is this statement right?

if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0))
// overflow
else
// not overflow

Oct 20 '05 #1
4 3545
aling wrote:
Given: signed a, b;
How to judge overflow of the sum of these two operands? Just use one
*if* statement.

Is this statement right?

if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0))
What's "sum"?
// overflow
else
// not overflow


You need to check the values *before* you attempt to add them:

if (INT_MAX - a < b) // will overflow when added

(it's the same as saying
if (a + b > INT_MAX)
without actually attempting to add them.)

And you need to amend this if they are both negative to

if (INT_MIN - a > b)

The final should be

if ( (a > 0 && b > 0 && INT_MAX - a < b) ||
(a < 0 && b < 0 && INT_MIN - a > b) )

// a+b would overflow (or underflow for negative)
else
// no over- or underflow

I am sure somebody will correct me if I made a mistake here.

V
Oct 20 '05 #2
aling wrote:
Given: signed a, b;
How to judge overflow of the sum of these two operands? Just use one
*if* statement.
Just one if statement? That must be a homework requirement. Don't
worry; the day will come when you will decide how many if statements
there will be, and get paid. :)
Is this statement right?

if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0))
// overflow
else
// not overflow


Actually, the sum does not need to be involved. And in fact, if you
have already computed the sum, it is too late. The overflow has
happened (the behavior on overflow is undefined in C++!)

A maximally portable, correct C++ program must not allow overflow to
occur. Here is one way.

#include <climits>

// ...

signed int a, b, c;

// ... assign values ...

if ((a > 0 && b > 0 && a <= INT_MAX - b) ||
(a < 0 && b < 0 && a >= INT_MIN - b))
{
// handle overflow case somehow
}
else
{
c = a + b; // safe
}

The test a <= INT_MAX - b is nothing more than the trivial algebraic
transformation of a + b <= INT_MAX, which avoids computing a + b!
You know that since b > 0 it's safe to subtract INT_MAX - b.

One thing you have to watch out for is that the INT_MIN value on a twos
complement system may have no positive counterpart: it's one less than
the additive inverse of INT_MAX. I.e. the unary minus operator may
overflow!!! E.g.

if (a == INT_MIN && INT_MIN < -INT_MAX) {
// -a will overflow!
} else {
c = -a; // okay.
}

For instance, given a 16 bit twos complement number system, the most
negative number that can be represented is -32768, or 0x8000. But 32768
cannot be represented, because it is 0x10000, out of range. The highest
value is 32767 or 0xFFFF.

If you actually compute the twos complement to invert 0x8000 (flip the
bits, add 1), you get back, guess what, 0x8000!

Oct 20 '05 #3

Kaz Kylheku wrote:
aling wrote:
Given: signed a, b;
How to judge overflow of the sum of these two operands? Just use one
*if* statement.


Just one if statement? That must be a homework requirement. Don't
worry; the day will come when you will decide how many if statements
there will be, and get paid. :)
Is this statement right?

if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0))
// overflow
else
// not overflow


Actually, the sum does not need to be involved. And in fact, if you
have already computed the sum, it is too late. The overflow has
happened (the behavior on overflow is undefined in C++!)


Unsigned integers in C++ do not overflow but instead "wrap around" in
value when their maximum representable value is exceeded. So converting
both operands to unsigned ints and then verifying that their sum is
both greater than either operand and less than MAX_INT should be enough
to detect overflow when adding signed ints:

unsigned sum = unsigned(a) + unsigned(b);

if ( sum > INT_MAX or sum < unsigned(a) or sum < unsigned(b))
{
// error overflow
}

Greg

Oct 21 '05 #4
On 20 Oct 2005 19:28:36 -0700, "Greg" <gr****@pacbell .net> wrote:

unsigned sum = unsigned(a) + unsigned(b);

if ( sum > INT_MAX or sum < unsigned(a) or sum < unsigned(b))
{
// error overflow
}


This test fails for a == b == -1.
--

Note that when the signs of a and b are different, no overflow can occur for a
+ b.

Otherwise, overflow occurs when a > INT_MAX - b (for a and b positive), or a <
INT_MIN - b (for a and b negative).

So a test may be:

if (a > 0 && b > 0) {
if (a > INT_MAX - b) {
// overflow
}
} else if (a < 0 && b < 0) {
if (a < INT_MIN - b) {
// overflow
}
}

Oct 22 '05 #5

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

Similar topics

5
1795
by: milton | last post by:
**** Post for FREE via your newsreader at post.usenet.com **** Compiled by Turboc 2.0,PC with win2000 main() { int a=32767; long b=a+1; printf("%d,%ld",a,b); }
34
16635
by: Andy | last post by:
Hi, Are 1 through 4 defined behaviors in C? unsigned short i; unsigned long li; /* 32-bit wide */ 1. i = 65535 + 3; 2. i = 1 - 3; 3. li = (unsigned long)0xFFFFFFFF + 3; 4. li = 1 - 3;
7
17783
by: Vivek Mohan | last post by:
Hi, I am using gcc, and I am a bit confused about the warning message I got when I compiled and ran this small code snippet - int main() { unsigned long x = 3*1024*1024*1024; /* 3GB */ printf(" %x ", x); } I got the following error,
14
2075
by: TTroy | last post by:
Hello, can anyone explain why the following function will not work for INT_MIN: /* itoa: convert n to characters in s */ void itoa(int n, char s) { int i, sign; if((sign = n) < 0) /* record sign */
27
4515
by: REH | last post by:
I asked this on c.l.c++, but they suggested you folks may be better able to answer. Basically, I am trying to write code to detect overflows in signed integer math. I am trying to make it as efficient as possible without resorting to assembly language, and without causing undefined behavior. That, of course, means catching the overflow...
3
1561
by: Unknown | last post by:
Why does this overflow? long testmath = (898 * 360 + 30) * 24 * 60 * 60 * 1000 / 25; but if I do it this way it works.. long testmath1 = (898 * 360 + 30) long testmath2 = testmath1 * 24 * 60 * 60 * 1000 / 25; How can I get it so that it works properly in the first definition..?
25
6222
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;
8
10654
by: starffly | last post by:
In my program, the caculated value is supposed to be no more than the constant named MAXINT,otherwise, overflow error will be informed.however, I cannot test if the value exceeds MAXINT within the integer scope smaller than MAXINT,so I want to seek a measure to test the excess without the value's comparing to MAXINT. Please let me know if you...
7
1891
by: quarkcode | last post by:
there is a function f i need to check whether the value returned by f is positive or negative but if the number overflows and shows negative even when actually it is positive how can i check that the number is really negative?
0
7614
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8125
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...
1
7676
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...
0
7974
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...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3642
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2114
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
1
1221
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.