Translated from 8940092
Implements the variable parameter function for C/C + + language.
Variable parameter function: void Fun (para,...)
The variable parameter function must have a fixed parameter.
 
defined in header file stdarg.h Three macros can be used: void Va_start (va_list arg, prev_ param );
type va_arg (va_list arg, type );
void va_end (va_list arg );
va here is the meaning of variable-argument (variable parameter) .
Then the implementation of the variable parameter function becomes relatively simple.
The general parameter function processing process:
① defines a va_list variable to be set to VA
The ② call Va_start () causes the VA to store the address of a fixed parameter before the variable parameter function.
③ constantly calls Va_arg () to make the VA point to the next variable parameter.
④ Last Call to Va_end () indicates that the argument processing is complete.
The principle is: the parameters of the function are stored in memory from the low address to the high address.
Look at an example: imitating the implementation of PRITNF:
#include <iostream>#include<stdarg.h>#include<string.h>using namespacestd;voidFuncChar*c,...) { intI=0; Doubleresult=0; Va_list Arg; //va_list VariableVa_start (ARG,C);//arg points to fixed parameter C while(c[i]!=' /'){ if(c[i]=='%'&&c[i+1]=='D') {printf ("%d", Va_arg (ARG,int)); I++; } Else if(c[i]=='%'&&c[i+1]=='F') {printf ("%f", Va_arg (ARG,Double)); I++; } Else { Charnewc[2] = {C[i]};//converts a character to a string output, or you can use Putchar ()printf"%s", NEWC); } I++; } va_end (ARG);}intMain () {intI= -; Doublej=100.0; printf ("%d be equal%f\n", i,j); Func ("%d be equal%f\n", i,j); }
C + + variable parameter function (RPM)