可变数量参数的传递

先看给小例子:
//
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值