Page 1 of 1

printf function

Posted: Fri Aug 13, 2004 12:41 pm
by Fedora
This aint really about OS dev, but anyways. I?ve written a printf function like:
void printf(const char *str, ...), works like printf in standard C. The problem is when I?d like to use a variabel inside it, like

printf("Your age is %d", 13);

This works great, but for float/doubles? In standard C you use %f for both of them, but how can I do this since doubles are 8 bytes and floats 4 (I need to catch the argument as one of those two types).

Re:printf function

Posted: Fri Aug 13, 2004 4:41 pm
by Dreamsmith
IIRC, when you have a function declared like this:

Code: Select all

void myfunc(const char *args, ...)
And you pass something like this:

Code: Select all

myfunc(args, mychar, myshort, myint, myfloat, mydouble);
mychar and myshort will be promoted to ints before being pushed, and myfloat will be promoted to a double.

Re:printf function

Posted: Sat Aug 14, 2004 2:18 am
by Solar
YRC. (You remember correctly.)

Re:printf function

Posted: Sat Aug 14, 2004 6:30 am
by Candy
How do you distinguish between 4-byte and 8-byte entries, and how can you arbitrarely define where the N-th entry begins?

Re:printf function

Posted: Sat Aug 14, 2004 7:17 am
by XStream
I thought that printf uses the arguments based on what is in the input string, for example:

Code: Select all

printf("Arg1: %f, Arg2: %d, Arg3: %s, Arg4: %f", float1, long1, string1, float2)
Printf would then see the first format tag '%f' and know that the first arg is 8 bytes long, the next tag '%d' would indicate the next arg is 4 bytes, the next tag '%s' would indicate 4 bytes, a string pointer, the last tag '%f' would indicate the next arg is 8 bytes long.

There is no other way that I know of to determine the size of each argument.

Cheers.

Re:printf function

Posted: Sat Aug 14, 2004 9:11 pm
by proxy
the answer is that is it promoted to a double, (so you pop 8 bytes off the stack) but with %f you simply print it with float precision.

and yes it is the format specifier string that determines the type/size of the variatic arguments, it's the only way to know.

proxy

Re:printf function

Posted: Sun Aug 15, 2004 12:40 am
by Dreamsmith
proxy wrote:the answer is that is it promoted to a double, (so you pop 8 bytes off the stack) but with %f you simply print it with float precision.
Make that double precision. Standard C specifies that %f indicates an argument of type double. There is no way in Standard C to specify a printf argument of type float.

Actually, the precision, unless specified, is six digits.