Furqan
Furqan

Reputation: 268

Why is this generating Floating point exception?

This is the second example of wikipedia SIGFPE page.

#include <limits.h>
int main(void)
{
    volatile int x=INT_MIN;
    volatile int y=-1;
    x=x/y;
    return 0;
}

It is inverting the sign to positive of INT_MIN. How can it be FPE?

Upvotes: 3

Views: 411

Answers (3)

Steve-o
Steve-o

Reputation: 12866

The Wikipedia article answers:

... triggers the signal because the quotient, a positive number, is not representable.

INT_MIN / -1 = -INT_MIN
             = INT_MAX + 1
             => invalid number
             => floating point exception (FPE)

Upvotes: 6

paxdiablo
paxdiablo

Reputation: 881093

As that page you link to points out, "although SIGFPE does not necessarily involve floating-point arithmetic, there is no way to change its name without breaking backward compatibility".

The reason you're getting the signal is because of the way two's complement numbers work. The range for a sixteen bit two's complement number (for example) is -32768..32767.

In other words, the 65,536 possible values are mapped to that range. If you try to negate INT_MIN, there is no representation that will give you the correct value (we don't have a 32768 available to us).

Ths is the case for all two's complement numbers: eight bits gives you -128..127, thirty two bits gives you -2147483648..2147483647.

In all those cases, INT_MIN does not have a positive equivalent.

Interestingly, the other two encoding schemes allowed for by ISO C (one's complement and sign/magnitude) have a direct one-to-one mapping between positive and negative values). Equally interesting, almost no-one uses them :-)

Upvotes: 1

john
john

Reputation: 87944

Did you read the wiki page? It maybe an FPE but it's not a floating point exception.

Although SIGFPE does not necessarily involve floating-point arithmetic, there is no way to change its name without breaking backward compatibility.

Upvotes: 1

Related Questions