By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,728 Members | 2,488 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,728 IT Pros & Developers. It's quick & easy.

Detecting overflow

P: n/a
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 help!
Nov 14 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
On Sun, 09 May 2004 19:47:07 -0400, Paul Emmons <pe*****@voicenet.com>
wrote in comp.lang.c:
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?
That depends on whether you are talking about signed or unsigned long
longs.
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 help!


There is no standard C way to detect overflow in signed integer types
or floating point types after it happens. The overflow itself
produces undefined behavior in these types, and the C standard no
longer places any requirements on the program.

Instead you need to check the values before hand. With the exception
of LLONG_MIN, it is not that hard. For addition there is no
possibility of an out-of-range answer if the signs of both values are
the different, for subtraction if they are the same.

If you are using unsigned long long, on the other hand, the result of
overflow or underflow is well-defined. The result is the true
arithmetic result modulo (ULLONG_MAX + 1).

So given unsigned long long values a and b, an overflow or underflow
has occurred if either:

a + b is less than a

a - b is greater than a

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #2

P: n/a
What you say makes sense. Thank you!

Nov 14 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.