Hello everyone,
I want to know is how to achieve the C language printf function parameter uncertainty principle(Of course, we do not use the system-supplied "stdarg.h" header file).
The following is "printf" function prototype:
_CRTIMP int __cdecl printf(const char *, ...);
I do not think it uses a function overloading methods,As you know, when users use printf parameters are uncertain (Such as, order uncertain parameter types, the numbers of parameters uncertain and so on).I try to guess it may be using the stack.
Regards,
Ken
Thank for you.
Loading


VulpesRank #55 · 29.2K reputationPosted Oct 21, 2013, 1:08 AM EDT
You can write these functions yourself but, to do so, you have to make use of an object of type va_list and the macros : va_start, va_arg and va_end all of which are defined in the "stdarg.h" header file. These enable you to iterate through the list of optional arguments and then clean up at the end.
I suppose you could define your own object type and macros, rather than use the standard ones, but there seems very little point.
If you're interested in writing your own version of printf (or a minimal version thereof), then there's an example on pages 155 and 156 of the second edition of K & R if you have this book.
Ken HRank #2,315 · 610 reputationPosted Oct 21, 2013, 10:50 PM EDT
I haven't the second edition of K & R.
VulpesRank #55 · 29.2K reputationPosted Oct 22, 2013, 1:32 AM EDT
However, here's an example of a 'varargs' function I've coded myself which calculates the mean of a series of non-zero numbers:
The output should be:
Ken HRank #2,315 · 610 reputationPosted Oct 22, 2013, 6:00 PM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 24, 2013, 2:55 AM EDT
Ken HRank #2,315 · 610 reputationPosted Oct 24, 2013, 3:18 PM EDT