C/C++ 可变参数函数

博客内容参考自 cplusplus

头文件解释

头文件名字:stdarg

英文原文解释:

Variable arguments handling
This header defines macros to access the individual arguments of a list of unnamed arguments whose number and types are not known to the called function.

A function may accept a varying number of additional arguments without corresponding parameter declarations by including a comma and three dots (,...) after its regular named parameters:

return_type function_name ( parameter_declarations , ... );
To access these additional arguments the macros va_start, va_arg and va_end, declared in this header, can be used:
  • First, va_start initializes the list of variable arguments as a va_list.
  • Subsequent executions of va_arg yield the values of the additional arguments in the same order as passed to the function.
  • Finally, va_end shall be executed before the function returns.

个人理解:

C/C++里面存在一种机制,可以使得函数可以接受可变参数,可变参数的意思是变量参数名未知、变量参数类型未知、变量参数数量未知。

函数声明方式是,第一个参数是一个符合语法的确定的参数,后接一个逗号以及三个英文符号的点(省略号)

return_type function_name ( parameter_declarations, ... );


使用方法

类型 va_list 定义用于接受可变参数的变量,然后通过 void va_start(va_list ap, paramN) 函数来初始化加下来的N个未知参数

然后通过  type va_arg(va_list ap, type) 函数来获取ap中的未知参数

在函数返回前要调用 void va_end(va_list ap) 函数来取回

可以通过 int vsprintf(char *s, const char *format, va_list ap); 函数来实现一种特殊用法,下面源码有具体的思想方法


实例

/* vsprintf example */
#include <stdio.h>
#include <stdarg.h>

void PrintFError ( const char * format, ... )
{
  char buffer[256];
  va_list args;
  va_start (args, format);
  vsprintf (buffer,format, args);
  perror (buffer);
  va_end (args);
}

int main ()
{
  FILE * pFile;
  char szFileName[]="myfile.txt";

  pFile = fopen (szFileName,"r");
  if (pFile == NULL)
    PrintFError ("Error opening '%s'",szFileName);
  else
  {
    // file successfully open
    fclose (pFile);
  }
  return 0;
}


* 具体情况可直接去cplusplus网站学习

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章