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应当初执行。
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。
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; }