473,406 Members | 2,705 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,406 software developers and data experts.

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 3539
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
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
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...
7
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 */...
14
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) /*...
27
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...
3
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 *...
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...
8
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...
7
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
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,...
0
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,...

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.