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網站學習

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