[gccsdk] [Bug 250] New: GCC 4.7.4 Rel 1 Dev 2014-01-08: sqrt function

Bob Brand bob.brand at tiscali.nl
Sat Mar 22 13:16:41 PDT 2014


Hello Duncan,

In message <bug-250-73 at http.www.riscos.info/bugzilla3/> you wrote:

>   printf("%f\n",sqrt(2.0));

Looks like you have fallen in a classic C pitfall:
passing a double argument to a vararg/stdarg function
but interpreting it as float.

Try either:
  printf("%lf\n", sqrt(2.0));
Or:
  printf("%f\n", (float) sqrt(2.0));

Reason: float is a four byte type, double is 8 bytes.
And even if it you'd use sqrtf() or fsqrt() (these
non-standard functions are not present in the RISC OS
version of the library as far as I know), standard C
would still promote the float argument to a double
before passing control to printf().

That in turn is presented with 8 bytes but the float
format only pulls 4, and interprets that as float.  So
any output would be possible.

(You may want to have a look at Andrew Koenig's book
`C Traps and Pitfalls'.  It was already an ancient book
when I was a student, but the traps and pitfalls haven't
changed since.)

Regards,

Bob.

-- 
Bob Brand




More information about the gcc mailing list