Jump to content
  • Advertisement
Sign in to follow this  
hkBattousai

[C] printf() - Infinite parameters?

This topic is 4452 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

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
Quote:

Is that mere overloading?

C doesn't have overloading, so if you are really using C++, beware -- listen to Fruny's advice.

Share this post


Link to post
Share on other sites
Check "safe printf" for example, to use with C++
http://www.boost.org/libs/format/doc/choices.html

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!