write your own function with varying arguments

This post is used to tell how to write your own function with varying arguments (如何写变参函数) – we will write our own ‘printf()’ function called ‘ddLog()’. Wish the code below would give you a hint:)

* This source file is used to show an example on
* writing function with a varying number of arguments
* of varying types, like printf() and snprintf().
* Originated: Jan 12, 2011
* dave.tian@alcatel-lucent.com

#include <stdio.h>
#include <string.h>
#include <stdarg.h>

/* var arg function declaration */
int ddLog( const char *, …);

int main( void)
int date = 20110112;
char at = ‘@’;

ddLog( “This is a demo function”
” used to show how to write”
” var arg function based on”
” ANSI stylen”
“daveti”, at, date);

return 0;

/* ddLog() is some kind of like printf() */
int ddLog( const char *msg, …)
char outPut[ 1000];
char *outP = outPut;
// Var arg structure
va_list argS;
// Determine if it is format string
char *percentP = NULL;
// Pointer for each arg
char *argP;
char argChar;
int argInt;

// Start var arg parsing
va_start(argS, msg);
while ( *msg != ”)
if ( *msg == ‘%’)
percentP = msg;

if ( percentP != NULL)
switch ( *msg)
case ‘s’: //string
argP = va_arg( argS, const char *);
outP += snprintf( outP, (1000+outPut-outP), “%s”, argP);
case ‘c’: //char
argChar = (char) va_arg( argS, int);
outP += snprintf( outP, (1000+outPut-outP), “%c”, argChar);
case ‘d’: //int
argInt = va_arg( argS, int);
outP += snprintf( outP, (1000+outPut-outP), “%d”, argInt);
// Un-supported format string
// Copy the ‘%’ and un-supported char here
*outP++ = ‘%’;
*outP++ = *msg;
percentP = NULL;

*outP++ = *msg++;

// Copy the ” at the end
*outP = ”;

// End var arg parsing

printf(“%s”, outPut);
return strlen( outPut);

About daveti

Interested in kernel hacking, compilers, machine learning and guitars.
This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s