Hi -
You're really asking three different questions:
1. Q: How can a function like "printf" handle a variable parameter list?
A: C/C++ supports "variadic arguments". Here's an explanation:
http://www.cprogramming.com/tutorial/c/lesson17.html
2. Q: How does printf know what kind of argument it's actually getting?
A: As you already observed - it doesn't. It assumes that the type you're giving it in your format string is correct - and bad things can happen if the format string is wrong. This is precisely why many C++ folks prefer type-safe alternatives like "cout".
3. Q: Why does C seem to give the correct real-number values even if I deliberately give it the incorrect type:
Code:
printf("%f",(double)1.2); /*(displaying a 8 byte double while expecting a 4 byte floating point number.*/
printf("%lf",1.2f); /* opposite of the above comment */
A: I honestly don't know. But it's still wrong - and the fact that it "seems" to work is a good example of what Steve O'Connell calls "programming by coincidence". Which is a Bad Thing.
Here's an example (compiled on Windows, under MSVC++) that confirms your observation:
Code:
#include <stdio.h>
int
main (int argc, char *argv[])
{
float f = 1.2f;
double d = 1.2;
printf ("%f, %s\n", (double)1.2, "ABC");
printf ("%lf, %s\n", 1.2f, "DEF");
printf ("sizeof f: %d, d: %d, float const= %d, double const= %d\n",
sizeof (f), sizeof (d), sizeof (1.2f), sizeof (1.2) );
return 0;
}
Quote:
1.200000, ABC
1.200000, DEF
sizeof f: 4, d: 8, float const= 4, double const= 8
|
If you were still curious, it would be interesting to:
a) Look at the assembly code (for example, "gcc -S") to see exactly what values are being passed in to "printf"
b) Look at the binary values (for example, under gdb) of "f" and "d".
c) Do some reading on "float" vs "double" representations:
http://www.codeguru.com/forum/printthread.php?t=323835
I would try these suggestions in
reverse order ("c", "b" and finally "a"), and I think you'll discover the answer ;-)
'Hope that helps ..
.. and have fun!
Your .. PSM