int Average(int val,...)
{
int total = 0;
int num;
int count = val;
va_list valist;
va_start(valist,val);
while(val)
{
num = va_arg(valist,int);
total = total + num;
val--;
}
va_end(valist); //据说不加这一句可能造成程序崩溃,但是这只是给一个char *指针赋值为空而已,没那么严重吧。
return total/count;
}
int main(int argc,char *argv[])
{
printf("%d\n",Average(3,1,2,3));
printf("%d\n",Average(5,1,2,3,6,13));
return 0;
}
参数个数不是有么?看va_start的宏也可以看到:#define va_start(ap,v) ( ap = (va_list)_ADDRESSOF(v) + _INTSIZEOF(v) ),跳过了一个int类型的长度,这个长度恰好就是第一个参数,看反汇编就更清楚了:
7.15 Variable arguments <stdarg.h> 1 The header <stdarg.h> declares a type and defines four macros, for advancing through a list of arguments whose number and types are not known to the called function when it is translated.