C/C++标准库 之 <cstdarg>

1.va_list

        1.1 引入头文件:#include <stdarg.h>

        2.1 作用:保存有关变量参数的信息

2.va_start

        2.1 引入头文件:#include <stdarg.h>

        2.2 声明式:void va_start(va_list ap, paramN);

        2.3 作用:初始化变量参数列表,初始化ap以检索参数paramN之后的附加参数

3.va_arg

        3.1 引入头文件:#include <stdarg.h>

        3.2 声明式:type va_arg(va_list ap, type)

        3.3 作用:检索下一个参数

4.va_end

        4.1 引入头文件:#include <stdarg.h>

        4.2 声明式:void va_end(va_list ap);

        4.3 作用:使用变量参数列表结束,执行适当的操作,以便于使用va_list对象ap检索其附加参数的函数正常返回。无论何时从该函数调用va_start,都应在函数返回之前调用该宏。

5.va_copy

        5.1 引入头文件:#include <stdarg.h>

        5.2 声明式:void va_copy(va_list dest, va_list src);

        5.3 作用:复制变量参数列表

Example:

#include <stdio.h>      /* printf, vprintf*/
#include <stdlib.h>     /* malloc */
#include <string.h>     /* strlen, strcat */
#include <stdarg.h>     /* va_list, va_start, va_copy, va_arg, va_end */

/* print ints until a zero is found: */
void PrintInts (int first,...)
{
  char * buffer;
  const char * format = "[%d] ";
  int count = 0;
  int val = first;
  va_list vl,vl_count;
  va_start(vl,first);
  
  /* count number of arguments: */
  va_copy(vl_count,vl);
  while (val != 0) {
    val=va_arg(vl_count,int);
    ++count;
  }
  va_end(vl_count);
  
  /* allocate storage for format string: */
  buffer = (char*) malloc (strlen(format)*count+1);
  buffer[0]='\0';
  
  /* generate format string: */
  for (;count>0;--count) {
    strcat (buffer,format);
  }
  
  /* print integers: */
  printf (format,first);
  vprintf (buffer,vl);
  
  va_end(vl);
}

int main ()
{
  PrintInts (10,20,30,40,50,0);
  return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值