例子很简单
(1)控制台工程
#include <stdarg.h> #include <stdio.h> int sum(int, ...); int main() { printf("Sum of 15 and 56 = %d", sum(2, 15, 56) ); return 0; } int sum(int num_args, ...) { int val = 0; va_list ap; int i; va_start(ap, num_args); for(i = 0; i < num_args; i++) { val += va_arg(ap, int); } va_end(ap); return val; }
运行结果:
(2)MFC的工程下
BOOL DebugTrace(LPCTSTR lpszFormat,...) { CString szMsg; va_list argList; va_start(argList, lpszFormat); CString para; while(1) { para = va_arg(argList, LPCTSTR); if(para == "") break; AfxMessageBox(para); } va_end(argList); return TRUE; }
调用时
void CVaMFCDemoDlg::OnButton1() { // TODO: Add your control notification handler code here DebugTrace("1", "a", "bc", "de", ""); }
参考:http://www.yiibai.com/c_standard_library/c_macro_va_arg.html