Serious bug

Joe Buck
Wed Sep 30 12:52:00 GMT 1998

> said:
> > Not to me. I was taught NEVER to use == or != with floating point,
> > because they simply don't make sense. Too bad that C[++] standard
> > allows them. 

== and != with floating point *do* make sense if used correctly.
"Never use == or != with floating point" is a wise rule to teach
a beginner, but == and != are safe and proper when used for values
that can be exactly represented, under circumstances where exact
values will occur.  Of course, programs that do this are only guaranteed
to work on processors that do IEEE floating point (though if overflows
are avoided they worked on the Vax as well).

> Actually, in ieee754 == and != have one very important use: they can be 
> used to test for a NaN without causing a fault.
> 	double a;
> 	...
> 	if (a != a)
> 	{ 
> 	  /* Code to deal with a NaN */
> 	}
> Comparing different floating point numbers for (in)equality is definitely 
> a no-no.

Given IEEE 754, comparing different floating point numbers for
(in)equality is perfectly safe when it is done only in cases where
we know that exact results are computed, e.g. in fixed point
computation, testing for zero where zero was explicitly stored
on one control path, etc.

More information about the Gcc mailing list