Hunt The Bug |
|
|
#include <stdio.h> #include <string.h> #include <stdlib.h> int main( void ) { float f; double d; f = strtof("5.7",NULL); d = strtod("5.7",NULL); printf("F: %f\n", f); printf("F: %f\n",(double)f); printf("D: %f\n", d); printf("D: %f\n",(double)d); return 0; } |
OK, so here's a fun thing - what do you think that code should print?
It prints this:
In case you're interested:
I've been corrected about this. Apparently it's not thought
of as being "built in" if the code is in libc. So I stand
(or sit) corrected. The code for strtof is in libc, or some
library (as yet not exactly pinned down) but the prototype
isn't in strlib.h.
The reason is becoming clear now. strtof wasn't in the original C and has only been introduced in C99. Since it is in C99 the code exists. Since it's not in earlier versions the prototype isn't declared unless you're in C99 mode. So there you are. |
However, the built-in version of strtof doesn't have a prototype unless you are in C99 mode, just in case you made one of your own, and hence the system defaults to returning an int.. But now one part of the compiler thinks it's an int, another thinks it's a float, and everything goes to hell in a handbasket.
So there are three ways to get answers you expect instead of random numbers:
Or don't use C.
Contents |
Links on this page |
|
Quotation from Tim Berners-Lee |