Nasty bug

Christopher R Volpe volpe at underdog.crd.ge.com
Fri Aug 31 03:05:35 AEST 1990


In article <0093BF08.7F3834E0 at rigel.efd.lth.se>, e89hse at rigel.efd.lth.se
writes:
|>void main()
|>{
|>    prnval("10.0",0.0);
|>    exit(0);
|>}
|>
|>prnval(s,f)
|>char   *s;
|>float   f;
|>{
|>   if(f == 0.0)
|>       sscanf(s,"%f",&f);
|>   printf("%10.2f\n",f);
|>}
|>
|>And it didn't work. Why? The answer is that the parameter f is a
|>double, not a float since all floats are converted to double when they are
|>passed as arguments to functions. 

It's true that f is promoted to double in the printf, but that's ok
because printf expects a double when it sees %f. It knows that floats
never get passed just as floats. 

Also, the scanf is ok here because you're passing a pointer to 
a float, and the %f tells scanf in this case that the argument is
a pointer to a float, not a double. So, the printf and scanf are
both ok here. I would expect that the problem is being caused
not by printf or by scanf, but by the fact that the formal parameter
to PRNVAL is declared as a float, when it is REALLY being passed
a double from main(). (Anyone out there agree/disagree with this????)

|>Therefore &f is a ptr to double rather than a
|>ptr to float as one would expect looking at the declartion. 

No, &f is still a ptr to float, not a ptr to double. Floats get
promoted, pointers don't. This isn't the problem.

|>Later I rewrote
|>prnval() as:
|>
|>prnval(s,f)
|>char *s;
|>double f;
|>{
|>   if(f == 0.0)
|>       sscanf(s,"%lf",&f);
|>   printf("%10.2f\n",f);
|>}

This is the correct solution anyway.
|>
|> Henrik Sandell
                                          
==================
Chris Volpe
G.E. Corporate R&D
volpecr at crd.ge.com



More information about the Comp.lang.c mailing list