Sign in to follow this  
hkBattousai

[C] printf() - Infinite parameters?

Recommended Posts

the function declaration for printf is something like

void printf(char* format,...);

the format is the string you pass in, the ... represents all the paramaters you pass in, to get to those parameters you do:

va_list myargs;
va_start(myargs, format);

this gets the paramaters for you, you pass in format because it just reads all the parameters on the stack after the format parameter you pass in. its not really infinite i dont think, as you could run out of stack space if you pass to0 many in.

This might be useful to you.

Share this post


Link to post
Share on other sites
printf is a variadic function.

It uses a couple of tricks with the C calling convention to figure out how many arguments it received:

* "caller cleanup" - the convention is that the caller is responsible for both pushing and popping the arguments on the stack. This is necessary of variadic functions since the callee itself wouldn't know how many parameters it received and so wouldn't be able to adjust the stack appropriately.

* "right-to-left parameter passing" - the leftmost (first) function argument is the last to be put on the stack, while the rightmost (last) is placed first. In C, variadic functions require at least one non-variadic parameter (i.e. the first one). Since it is at the "far end" of the parameter list, if you know where it is, which is the job of the va_start and va_end macros used to implement variadic functions, you can over them (using va_arg) to extract them one by one - assuming you know their types. Variadic functions are very type-unsafe and should never be used with C++ (non-POD) objects.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this