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);
    }
    va_end(args);
    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.


Actions

Information

4 responses

27 07 2013
Santos

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 comment