printf function

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
Fedora

printf function

Post 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).
Dreamsmith

Re:printf function

Post 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.
User avatar
Solar
Member
Member
Posts: 7615
Joined: Thu Nov 16, 2006 12:01 pm
Location: Germany
Contact:

Re:printf function

Post by Solar »

YRC. (You remember correctly.)
Every good solution is obvious once you've found it.
User avatar
Candy
Member
Member
Posts: 3882
Joined: Tue Oct 17, 2006 11:33 pm
Location: Eindhoven

Re:printf function

Post 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?
XStream

Re:printf function

Post 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.
proxy

Re:printf function

Post 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
Dreamsmith

Re:printf function

Post 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.
Post Reply