Variable Arguments: stdarg.h

I l @ ve RuBoard

Variable Arguments: stdarg.h

The stdarg.h header file provides a means for defining a function having a variable number of arguments. The prototype for such a function should have a parameter list with at least one parameter followed by ellipses:

 void f1(int n, ...);                 /* valid   */ int f2(int n, const char * s, ...);  /* valid   */ double  f3(...);                     /* invalid */ 

In the following, the term lastparm is the identifier used for the last parameter preceding the ellipses. In the preceding examples, lastparm would be n for the first case and s for the second case.

The header file declares a va_list type to represent a data object used to hold the parameters corresponding to the ellipses part of the parameter list. Table F.11 lists three macros to be used in the function with the variable parameter list. An object of type va_list should be declared before using these macros.

Table  F.11. Variable argument list macros.
Prototype Description
void va_start(va_list ap, lastparm ); This macro initializes ap before use by va_arg () and va_end() ; lastparm is the identifier for the last named parameter in the argument list.
type va_arg(va_list ap, type ); This macro expands to an expression having the same value and type as the next item in the argument list represented by ap ; type is the type for that item. Each call advances to the next item in ap .
void va_end(va_list ap); This macro closes out the process and may render ap unusable without another call to va_start() .

Here is a short example of how the facilities can be used to create a function that sums a variable number of arguments; here, the first argument to sum() is the number of items to be summed.

 #include <stdio.h> #include <stdarg.h> double sum(int, ...); int main(void) {   double s,t;   s = sum(3, 1.1 ,2.2,3.3);   t = sum(6, 1.1,2.1,3.1,4.1,5.1,6.1);   printf("%f %f\n", s, t);   return 0; } double sum(int lim,...) {   va_list ap;                   /* declare object to hold arguments  */   double tot = 0;   int i;   va_start(ap, lim);            /* initialize ap to argument list    */   for (i = 0; i < lim; i++)      tot += va_arg(ap, double); /* access each item in argument list */   va_end(ap);                   /* clean up                          */   return tot; } 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net