Question

I know signed overflows in C are undefined behavior according to the standard, but since in practice it is quite common to use 2's complement for signed integers (and even allowed, for instance using the -fwrapv option in gcc), I'd like to find a list of examples of programs which make good use of this fact.

Programs such as "incrementing counters that occasionally overflow" seem more appropriate for unsigned integers, so I don't think they count.

Also, I'm not considering compiler optimizations that could be enabled in this case, but useful programs that actually use signed overflow to compute something interesting.

Was it helpful?

Solution

We used integer overflow to implement 64-bit arithmetic on 32-bit CPUs (in C and C++, way back in the 1980s). Off the top of my head, I think it was coded something like this:

// Add two-word integers
void add64(unsigned a[2], unsigned b[2])
{
    unsigned    t;

    // Add two-word integer b to a
    t = a[1];
    a[1] += b[1];    // Lower word
    if (a[1] < t)    // True if a[1]+b[1] overflows
        a[0]++;      // Upper word
}

Now, granted, this is not using signed integer overflow, but I think we did in fact have signed integer forms of these routines as well, based on the same principle of detecting overflow to adjust the final result. (I just can't recall the details at the moment.) Most of the routines were actually coded as C preprocessor macros, as I recall.

OTHER TIPS

After discussing with a colleague at work (who has no StackOverflow account), he pointed me to this site:

http://www.gnu.org/software/autoconf/manual/autoconf-2.67/html_node/Signed-Overflow-Examples.html#Signed-Overflow-Examples

I accepted @David R Tribble's answer since it is a "real world" example of signed overflow, but I leave the link here as reference as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top