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); }
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.
Thank you Santos
Excellent site you have here.. It’s difficult to find high quality writing like yours nowadays.
I really appreciate individuals like you! Take care!!
Thank you very much.