How to pass variable number of arguments to a function

30 04 2013

How to write functions which takes variable number of arguments in our program.

In C++, we can write functions with three dots(…) as parameter. This will make that function to support variable number of arguments. The va_arg, va_end, and va_start macros provide access to function arguments when the number of arguments is variable.

void LogError(TCHAR * format, ...)
   va_list args;
   int len;
   TCHAR *buffer;

   va_start(args, format);
   len = _vscprintf(format, args) + 1;
   buffer = (TCHAR *) _alloca( len * sizeof(TCHAR) );
   vsprintf_s( buffer, len, format, args );
   CString strErrMsg = buffer;

int Sum(int noOfArgs, ...)
    int nSum = 0;
    va_list args;
    va_start(args, noOfArgs);
    nSum = va_arg(args, int);
    for(int i = 2; i <= noOfArgs; i++) 
        nSum += va_arg(args, int);
    return nSum;

void main()
    int nSum = Sum(5, 1, 2, 3, 4, 5);
    LogError(_T("Failed - %s, ErrorCode - %d"), "AccessDenied", 111);

These macros are defined in STDARG.H file.



4 responses

27 07 2013

I really like what you guys are up too. This kind of clever work and reporting!
Keep up the very good works guys I’ve incorporated you guys to blogroll.

28 07 2013
Sanoop S P

Thank you Santos

15 09 2013
farmville tutorial

Excellent site you have here.. It’s difficult to find high quality writing like yours nowadays.
I really appreciate individuals like you! Take care!!

18 09 2013
Sanoop S P

Thank you very much.

Leave a Reply to Sanoop S P Cancel reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: