views:

443

answers:

4

I'm getting the slope of a line bounded by two points

float slopeXY(CGPoint p1, CGPoint p2)
{
    return ((p2.y - p1.y) / (p2.x - p1.x));
}

If I give it a zero-sized line,

CGPoint p1 = CGPointMake(0, 10);
CGPoint p2 = CGPointMake(0, 10);

float sxy = slopeXY(p1, p2);

I don't get a divide by zero error.

+16  A: 

With the default floating-point environment on OS X, floating-point division by zero does not cause a trap or exception. 0.0/0.0 will instead return a NaN and raise the invalid floating-point status flag in the fpscr. Dividing a non-zero value by 0.0 will return an infinity and raise the divide-by-zero flag.

You can check for these conditions, if you need to, using the isnan( ) and isinf( ) functions defined in math.h

Stephen Canon
+3  A: 

Divide by zero error only happens for integer division. For float, normally you get infinity, unless the dividend is zero.

RichN
+1  A: 

Floating-point errors typically do not raise an exception.

rlbond
+1  A: 

Because it's Undefined Behavior. Your program is allowed to behave in any way, which may include crashing or showing us the last glimpse of the universe you so inconsiderately destroyed by dividing-by-zero.

From the C[99] Standard, §6.5.5.5:

The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined.

aib
The behavior is *not* undefined, because the OS X compilers conform to Annex F of the same standard. Section F.3.1 of C[99] says "the +, −, *, and / operators provide the IEC 60559 add, subtract, multiply, and divide operations," and IEC60559/IEEE-754 specifies the result of division by zero.
Stephen Canon
Oh. Is that just for floats, then?
aib