Detecting overflow

P

Paul Emmons

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!
 
J

Jack Klein

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top