New floating point puzzle

braner braner at batcomputer.tn.cornell.edu
Fri Aug 19 03:39:20 AEST 1988


[]

The new FP puzzling output is due to the fact that (old) C does not check
the type of parameters passed to functions, and the function takes the
parameters off the stack _assuming_ what their types are and therefore
how many bytes they occupy on the stack.  Thus, when printf() sees a "%x"
it takes sizeof(int) (usually 4) bytes off the stack.  In the case
printf ("%x %f", f, g) where f,g are floats, the "%f" _could_ get g
correctly _if_ sizeof(int)==sizeof(float) (usually true) and _if_
a float is actually passed (usually false: f,g are converted to doubles
before passing).  What actually happened was that the "%x" took the first
4 bytes of ((double) f) off the stack, and the "%f" took the latter 4 bytes
of ((double) f) plus the first 4 bytes of ((double) g).  The "%f" saw
a 0 in what it interpreted as the exponent field (really the mantissa tail
attached to 'f' when converting it to double) and concluded that the second
parameter is a 0.  The results would have been different (but still garbage)
in a machine with the opposite word ordering in a double, where the first
word is the less significant part of the mantissa.

- Moshe Braner

Message for nitpickers:  I did not mean to imply that _all_ C compilers
pass function parameters on the stack, nor that _all_ machines _have_ a
stack at all!



More information about the Comp.lang.c mailing list