不定长参数序列使用方法

这个例子用来求几个数的平均 数:

/*
** Compute the average of the specified number of values.
*/


#include 
< stdarg.h >

float  average(  int  n_values, ... )
{
 va_list var_arg;
 
int count;
 
float sum = 0;

 
/*
 ** Prepare to access the variable arguments.
 
*/

 va_start( var_arg, n_values );

 
/*
 ** Add the values from the variable argument list.
 
*/

 
for( count = 0; count < n_values; count += 1 ){
  sum 
+= va_arg( var_arg, int );
 }


 
/*
 ** Done processing variable arguments.
 
*/

 va_end( var_arg );

 
return sum / n_values;
}


 

在MSDN中我找到了解读这一段代码最权威的说明:

type va_arg( va_list arg_ptr, type );

void va_end( va_list arg_ptr );

void va_start( va_list arg_ptr );   (UNIX version)

void va_start( va_list arg_ptr, prev_param );   (ANSI version)

Return Value 返回值

va_arg returns the current argument; va_start and va_end do not return values.

 

Remarks

The va_arg, va_end, and va_start macros provide a portable way to access the arguments to a function when the function takes a variable number of arguments.

va_arg

Macro to retrieve current argument

va_end

Macro to reset arg_ptr

va_list

typedef for pointer to list of arguments defined in STDIO.H

va_start

Macro to set arg_ptr to beginning of list of optional arguments (UNIX version only)

 

The ANSI C standard macros, defined in STDARG.H, are used as follows:

  • All required arguments to the function are declared as parameters in the usual way. va_dcl is not used with the STDARG.H macros.

  • 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.

  • After all arguments have been retrieved, va_end resets the pointer to NULL.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值