例如:
void ConnectData(int i,...)
在上面的代碼中,編譯器只檢查第一個參數是否爲整型,而不對其他參數進行檢查。
對於可變參數的函數,需要進行特殊的處理。首先需要引用 <stdarg.h> 頭文件,然後利用va_list類型和va_start、va_arg、va_end 3個宏讀取傳遞到函數中的參數值。
這幾個宏的定義如下(在 ANSI C 中):
type va_arg( va_list arg_ptr, type );
void va_end( va_list arg_ptr );
void va_start( va_list arg_ptr, prev_param );
說明如下:
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_start函數將參數arg_ptr設置爲可變參數列表的第一個參數。參數arg_ptr的類型必須爲va_list。參數prev_param是在可變參數列表之前的那一個參數。(也就是說在 ANSI C 中,如果一個函數有可變參數,那麼在該可變參數前必須有一個明確定義的參數,否則無法調用函數 va_start ,例如函數 int add(int i,...)是合法的,而函數 int add(...)是不合法的。)】
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_arg函數將返回 arg_ptr 所指位置的值,並將 arg_ptr 指向下一個參數 】
va_end
After all arguments have been retrieved, va_end resets the pointer to NULL.
示例代碼:
#include<cstdarg>
#include<iostream>
using namespace std;
int add(int pre,...) //求和函數
{
va_list arg_ptr;
int sum=0;
int nArgValue;
sum+=pre;
va_start(arg_ptr,pre);
do
{
nArgValue=va_arg(arg_ptr,int);
sum+=nArgValue;
}while(nArgValue!=0); //自定義結束條件是輸入參數爲0
va_end(arg_ptr);
return sum;
}
int main()
{
cout<<add(1,2,3,0)<<endl; //必須以0結尾,因爲參數列表結束的判斷條件是讀到0停止
return 0;
}