Nasty bug

Paul Nulsen pejn at wolfen.cc.uow.oz
Fri Aug 31 12:56:00 AEST 1990


wallace at ynotme.enet.dec.com (Ray Wallace) writes:

>In article <0093BF08.7F3834E0 at rigel.efd.lth.se>, e89hse at rigel.efd.lth.se
>writes... 
>>... Therefore &f is a ptr to double rather than a
>>ptr to float as one would expect looking at the declartion.

>Sounds like a compiler bug to me.

I am not sure what the standard says, but this is definitely not a compiler
bug. With old K&R style declarations the compiler does not know the type of
a function argument until it sees the function definition. The function can
be invoked before the definition is known, and hence before the argument
types are known. In the case of floating point numbers, to avoid the
problems this creates the approach adopted was to promote all floating point
types to the common type of double. With ANSI style declarations this is no
longer necessary.

Compilers that accept ANSI style declarations have to accept the old style
as well for backward compatibility, and if they are going to do this
properly then they need to treat old style function definitions in the
manner that they would have been treated, i.e. they have to promote all
floats to doubles. This is what most compilers do. You will find that if you
use ANSI style declarations the problem does not arise.

I am surprised at the claim that VAX C does not promote the float to a
double, for the reasons I have just outlined. Did you use the old style
function definition in your test?

As someone who does a lot of number crunching, I can tell you that the
handling of floats in C is an significant obstacle to its use for heavy
floating point computations. Argument promotion is one of a number of
related gotcha's that make it difficult to write efficient single precision
floating point code. If you just need a few numbers, doubles are fine, but
when you are handling large data sets, the space and speed penalties can be
serious. ANSI declarations solve the problem of automatic promotion, but
there are of others. For example, the fact that floating constants are
doubles combined with the rules for type promotion in expressions means that
the following code
	float a, r;
	a = 3.1415926535 * r * r;
results in the promotion of r (at least once) and then the demotion of the
result back to float. To avoid this kind of trouble every constant has to be
cast:
	a = (float) 3.1415926535 * r * r;
which is a real pain.

If you aren't pressed for time and space always use double's - you will
probably end up using them whether you know it or not. If you are pressed
for space or time and have to use float's, then pity you.

Paul Nulsen
pejn at wolfen.cc.uow.edu.au



More information about the Comp.lang.c mailing list