[C] printf() - Infinite parameters?

Started by
3 comments, last by peous 17 years, 6 months ago
Can anyone explaing how come printf() can take unpredefined number of parameters? Is that mere overloading?
Advertisement
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.
Quote:Original post by BosskIn Soviet Russia, you STFU WITH THOSE LAME JOKES!
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Quote:
Is that mere overloading?

C doesn't have overloading, so if you are really using C++, beware -- listen to Fruny's advice.
Check "safe printf" for example, to use with C++
http://www.boost.org/libs/format/doc/choices.html

This topic is closed to new replies.

Advertisement