On 16 Jul., 11:51, "Bartc" <b...@freeuk.co mwrote:
<thomas.mer...@ gmx.atwrote in message
news:e2******** *************** ***********@d77 g2000hsb.google groups.com...
Is it possible to use some C or compiler extension to catch
integer overflow?
I know that a check before every integer computation
could be used to recognice an overflow, but it is not my
intention to slow down normal computations.
I don't think an integer overflow would typically cause a hardware
exception.
Maybe it is possible to switch the hardware to a some
mode where an interrupt is raised with an integer overflow.
In that case the code for the mode switch and the
interrupt handler would be compiler/os dependend, but
the rest of the program would be plain C.
So this is down to using extra instructions, usally /after/ the operation.
This need not be a high overhead, if you were targetting x86 instead of C,
you might use 'jo label' after the add.
Is 'jo' an actual x86 instruction meaning "Jump when overflow
flag is set"?
But C doesn't normally have this sort of thing built-in, unless it's in the
form of special compiler extensions and switches. In your case, you cannot
rely on this because your application then becomes compiler-specific (you
might as well rely on inline Asm).
I know that this will probably be compiler-specific.
This is just a thing I want to explore.
What about C99 or the next C standard?
There might be a few workarounds in C, but I guess they all have overheads
of some kind.
What is the purpose of this overflow check? To switch over to large integer
form? Otherwise overflow checking could be optional for the user.
It is not my intention to switch to larger integers
on the fly. I just want to avoid undefined behaviour.
The C89 Ansi C standard states:
The handling of overflow, divide check and other exceptions
in expression evaluation is not defined by the language.
Most existing implementations of C ignore overflow in
evaluation of signed integral expressions and assignments,
but this behavior is not guaranteed.
I think that exceptions for integer overflows could
also be helpful to find bugs.
Like other range checks (for array or string access) it
could be made optional. A compiler switch or pragma could
be used to switch it on or off.
Currently I am still hoping for a zero overhead solution.
Greetings Thomas Mertes
Seed7 Homepage:
http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.