•  Back 
  •  C Language 
  •  Index 
  •  Tree View 
  •  Cross references 
  •  Help 
  •  Show info about hypertext 
  •  View a new file 
Topic       : C-Language Documentation
Author      : John Kormylo
Version     : C.HYP 1.0
Subject     : Documentation/C-Language
Nodes       : 233
Index Size  : 6362
HCP-Version : 3
Compiled on : Atari
@charset    : atarist
@lang       : en
@default    : 
@help       : Help
@options    : +g -i -s +x +z -t4
@width      : 75
View Ref-File[ Variable Argument Lists ]

... allow you to define functions where the number and type of the
arguments can vary from call to call.  For example, printf and scanf
use variable argument lists.

To define a function with a variable argument list, simply use '...'
as the last argument in the list.  At least one other argument is
required, so that by using it (and possibly others) the function can
determine how many and what type of arguments to expect.

Within the function, call the function (actually, a macro)

  va_start(ap, parmN);

where 'ap' is a void pointer and 'parmN' isn't used in Pure C's
implementation.  One can then extract the extra parameters one
at a time from left to right using the function call

  parm = va_arg(ap, type);

where 'type' is the data type of parameter 'parm'.  Finally, call

  va_end(ap);

for portability (with Pure C it does nothing).  These macro's are
defined in header file STDARG.H (see #include).

Note: Using '...' forces the remaining arguments to be passed on the
      stack.  And as part of the ANSI standard, char's will be
      converted to int's and float's will be converted to double's
      before being passed (so never use char or float with va_arg).

Example:

/* Return the largest of n doubles */

double dmax(int n, ...)
 {
  void *ap;
  double max, parm;

  if(n < 1) return(-DBL_MAX);
  va_start(ap, n);
  max = va_arg(ap, double);
  while(--n) {
    parm = va_arg(ap, double);
    if(parm > max) max = parm;
   }
  va_end(ap);
  return(max);
 }