1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
// variable number of function arguments
#include<iostream>
#include <string>
#include <cstdarg>
using namespace std;
int sum(int count, ...)
{
if(count <= 0)
return 0;
va_list arg_ptr;
va_start(arg_ptr, count);
int sum = 0;
for(int i=0; i<count; ++i)
sum += va_arg(arg_ptr, int);// argument type determined here. It can vary!
va_end(arg_ptr);
return sum;
}
int main(void)
{
cout << sum(6, 2, 4, 6, 8, 10, 12) << endl;// 7 args. 1st gives # of args to follow
cout << sum(9, 11, 22, 33, 44, 55, 66, 77, 88, 99) << endl;// 10 args
cout << endl;
return 0;
}
|