C 语言的可变参数

type va_arg( va_list arg_ptr, type );
void va_end( va_list arg_ptr );
void va_start( va_list arg_ptr, prev_param );
va_start 
sets arg_ptr to the first optional argument in the list of arguments passed to the function. 
The argument arg_ptr must have va_list type. The argument prev_param is the name of the 
required parameter immediately preceding the first optional argument in the argument list.
 If prev_param is declared with the register storage class, the macro’s behavior is undefined. 
 va_start must be used before va_arg is used for the first time.


va_arg 
retrieves a value of type from the location given by arg_ptr and increments arg_ptr to point to
 the next argument in the list, using the size of type to determine where the next argument 
 starts. va_arg can be used any number of times within the function to retrieve arguments
  from the list.

va_end
After all arguments have been retrieved, va_end resets the pointer to NULL.

#include <stdio.h>
#include <stdarg.h>

double average(int num,...)
{

    va_list valist;
    double sum = 0.0;
    int i;

    /* 为 num 个参数初始化 valist */
    va_start(valist, num);

    /* 访问所有赋给 valist 的参数 */
    for (i = 0; i < num; i++)
    {
       sum += va_arg(valist, int);
    }
    /* 清理为 valist 保留的内存 */
    va_end(valist);

    return sum/num;
}

int main()
{
   printf("Average of 2, 3, 4, 5 = %f\n", average(4, 2,3,4,5));
   printf("Average of 5, 10, 15 = %f\n", average(3, 5,10,15));
}


上一篇:MongoDB(06):文档操作


下一篇:VS2015装西红柿插件时遇到的:未能正确加载“Visual Assist”包