I. Variable Parameter instances
# Include "stdio. H "/* function parameters are accessed in the form of Data Structure" stack ", from right to left. eg: */void fun (int ,...) {int * temp = & A; temp ++; int I; for (I = 0; I <A; ++ I) {printf ("% d \ n ", * temp); temp ++ ;}} int main () {int A = 1; int B = 2; int c = 3; int d = 4; fun (4, a, B, C, D); Return 0 ;}
Ii. Use of va_list
Va_start points argp to the first optional parameter.
Va_arg returns the current parameter in the parameter list and points argp to the next parameter in the parameter list.
Va_end clears the argp pointer to null.
The function can traverse these parameters multiple times, but they must start with va_start and end with va_end.
#include <stdio.h>#include <string.h>#include <stdarg.h>int demo( char *msg, ...){va_list argp;int argno = 0;char *para;va_start(argp, msg);while (1){para = va_arg(argp,char*);if (strcmp(para, "") == 0)break;printf("Parameter #%d is:%s\n", argno, para);argno++;}va_end( argp );return 0;}int main( void ){demo("DEMO", "This", "is", "a", "demo!","");}
3. Custom use
# Include <stdio. h> # include <string. h> # include <stdarg. h> void myprintf (char * FMT ,...) {char * parg = NULL; char C; parg = (char *) & FMT; parg + = sizeof (FMT); do {// judge each character, until the end of the entire statement C = * FMT; If (C! = '%') Putchar (c); else {Switch (* ++ FMT) {Case 'D': printf ("% d", * (int *) parg); break;} parg + = sizeof (INT);} + + FMT;} while (* FMT! = '\ 0'); parg = NULL; // va_end} int main (void) {myprintf ("The Fist: % d \ nthe secound: % d \ n ", 1, 2 );}
Iv. Details
In the include file of VC ++ 6.0, there is an stdarg. h header file, which has the following macro definitions:
# DEFINE _ intsizeof (N) (sizeof (n) + sizeof (INT)-1 )&~ (Sizeof (INT)-1 ))
# Define va_start (AP, V) (AP = (va_list) & V + _ intsizeof (V) // address of the first optional parameter # define va_arg (AP, T) (* (T *) (AP + = _ intsizeof (t)-_ intsizeof (t) // The next parameter address # define va_end (AP) (AP = (va_list) 0) // set the pointer to invalid
#include <iostream>#include <stdarg.h> const int N=5;using namespace std; void Stdarg(int a1,...){ va_list argp; int i; int ary[N]; va_start(argp,a1); ary[0]=a1; for(i=1;i< N;i++) ary[i]=va_arg(argp,int); va_end(argp); for(i=0;i< N;i++) cout<<ary[i]<<endl;} void main(){ Stdarg(5,12,64,34,23);}