doubles used as booleans
Lloyd Kremer
kremer at cs.odu.edu
Fri Mar 31 05:48:53 AEST 1989
Can a double be used directly as a boolean?
A few years ago, when DOS C compilers were in their infancy, I
was hand optimizing the code of one of our products so that it
would still fit in the standard 256K of an IBM XT.
(I said it was a few years ago :-) )
The optimizing in the compilers I was using was minimal, and I
found that substitutions such as 'if(i)' instead of 'if(i != 0)',
and 'if(!n)' in place of 'if(n == 0)' produced smaller code for
integral types. When I tried to extend this technique to floating
types where the potential gains were even greater (floating point
comparisons were expensively implemented), the code broke completely.
For example, if I had
double a, b;
.
.
if ( a && b ) /* meaning if(a != 0.0 && b != 0.0) */
statement;
the entire code fragment silently miscompiled.
But if I changed the condition to
( !!a && !!b )
or to
( !( !a || !b ) )
it compiled fine!
Even K&R 1 states that the ! operator can be applied to any type,
so I believe the latter examples are required to work, but what
about the first one? Would these compilers be officially broken
by today's standards?
Pray, what sayeth the pANS?
If it means anything, doubles were implemented as IEEE 754
64-bit reals, where 0.0 was represented by a zero-bit pattern.
Maybe that's the only reason the latter cases worked! :-)
Lloyd Kremer
Brooks Financial Systems
{uunet,sun,...}!xanth!brooks!lloyd
More information about the Comp.lang.c
mailing list