va_list
Type to holdinformation about variable arguments
This type is used as a parameter for the macros definedin cstdarg to retrieve the additional arguments of a function.
類型va_list用於檢索函數中附加的參數,作爲定義在cstdarg中的宏的參數使用。
Each compiler may implement this type in its own way. Itis only intended to be used as the type for the object used as first argumentfor the va_start, va_arg and va_endmacros.
va_startis in charge of initializing an object of this type, so that subsequent callsto va_arg with it retrieve the additional arguments passed tothe function.
每個編譯器都會使用它自己的方式實現這個類型。我們只需要把它作爲一種類型用於va_start, va_arg, va_end的第一個參數。Va_start負責初始化這種類型的一個對象,之後由va_arg負責檢索傳給函數的其它附加參數。
Before a function that has initialized a va_listobject with va_start returns, the va_endshall be executed.
在一個函數利用va_start初始化va_list對象後,va_end應當初執行。
va_start
void va_start ( va_list ap, paramN );
Initialize a variable argument list: 初始化一個變量參數列表
Initializes the objectof type va_list passed asargument ap to hold the information needed to retrieve the additionalarguments after parameter paramN with function va_arg.
初始化作爲參數ap傳入的類型爲va_list的對象,這個對象將用於函數va_arg中檢索在參數paramN後的附加參數的信息。
A function that executes va_start, shall also execute va_end before it returns.
一個執行va_start的函數也應該在返回前執行va_end。
Parameters
ap: Object of type va_list that will hold theinformation needed to retrieve the additional arguments with va_arg.
paramN: Parametername of the last named parameter in the function definition.
函數定義中最後一個參數的參數名。
/* va_start example */
#include <stdio.h>
#include <stdarg.h>
void PrintFloats ( int amount, ...)
{
int i;
double val;
printf ("Floats passed: ");
va_list vl;
va_start(vl,amount);
for (i=0;i<amount;i++)
{
val=va_arg(vl,double);
printf ("\t%.2f",val);
}
va_end(vl);
printf ("\n");
}
int main ()
{
PrintFloats (3,3.14159,2.71828,1.41421);
return 0;
}
/* va_arg example */
#include <stdio.h>
#include <stdarg.h>
int FindMax ( int amount, ...)
{
int i,val,greater;
va_list vl;
va_start(vl,amount);
greater=va_arg(vl,int);
for (i=1;i<amount;i++)
{
val=va_arg(vl,int);
greater=(greater>val)?greater:val;
}
va_end(vl);
return greater;
}
int main ()
{
int m;
m= FindMax (7,702,422,631,834,892,104,772);
printf ("The greatest one is: %d\n",m);
return 0;
}
/* va_arg example */
#include <stdio.h>
#include <stdarg.h>
void PrintLines ( char* first, ...)
{
char* str;
va_list vl;
str=first;
va_start(vl,first);
do {
printf ("%s\n",str);
str=va_arg(vl,char*);
} while (str!=NULL);
va_end(vl);
}
int main ()
{
PrintLines ("First","Second","Third","Fourth",NULL);
return 0;
}