先看给小例子:
//
#include "windows.h"
#include "stdio.h"
int Sum(int nFirst, ... )
{
int nResult = 0;
int nCur = 0;
va_list vaParam; // 建立指向可变参数的指针
va_start(vaParam, nFirst); //为该指针实例化
nCur = nFirst;
while( nCur != -1 )
{
nResult+=nCur;
nCur = va_arg(vaParam, int);//取得当前参数值,详见下面解释
}
va_end(vaParam); //
return nResult;
}
void main( void )
{
printf("Result = %d/n", Sum(1,2,3,-1));
}
-----------------------------------------
输出是 Result = 6
/
va_list: 定义一个指向可变参数的指针;
va_start:
void va_start( // va_start函数原型
va_list arg_ptr, // va_list类型的变量
prev_param // 第一个参数,如上例的nFirst
);
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:
type va_arg( // va_arg函数原型
va_list arg_ptr, // va_list类型的变量
type // 要获取的变量类型,如上例的int
);
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:
void va_end( // va_end函数原型
va_list arg_ptr // va_list类型的变量
);
After all arguments have been retrieved, va_end resets the pointer to NULL.
Email: _leo@live.cn