delorie.com/djgpp/doc/libc/libc_849.html   search  
libc.a reference

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

varargs

Syntax

 
#include <stdarg.h>

void va_start(va_list ap, LAST_REQUIRED_ARG);
TYPE va_arg(va_list ap, TYPE);
void va_end(va_list ap);

Description

Used to write functions taking a variable number of arguments. Note that these are actually macros, and not functions. You must prototype the function with `...' in its argument list. Then, you do the following:

Be aware that your function must have some way to determine the number and types of the arguments. Usually this comes from one of the required arguments. Some popular ways are to pass a count, or to pass some special value (like NULL) at the end.

Also, the variable arguments will be promoted according to standard C promotion rules. Arguments of type char and short will be promoted to int, and you should retrieve them as such. Those of type float will be promoted to double.

Return Value

va_arg returns the argument it fetched, the other macros return nothing.

Portability

ANSI/ISO C C89; C99
POSIX 1003.2-1992; 1003.1-2001

Example

 
int find_the_sum(int count, ...)
{
  va_list ap;
  int i;
  int total = 0;
  
  va_start(ap, count);
  for (i = 0; i < count; i++)
      total += va_arg(ap, int);
  va_end(ap);
  return total;
}

int other_function(void)
{
  return find_the_sum(6, 1, 2, 3, 4, 5, 6);
} 


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright © 2004     Updated Apr 2004