@node varargs, misc @subheading Syntax @example #include void va_start(va_list ap, LAST_REQUIRED_ARG); TYPE va_arg(va_list ap, TYPE); void va_end(va_list ap); @end example @subheading 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 `@dots{}' in its argument list. Then, you do the following: @itemize @bullet @item Create a variable of type @code{va_list}. @item Initialize it by calling @code{va_start} with it and the name of the last required (i.e. non-variable) argument. @item Retrieve the arguments by calling @code{va_arg} with the @code{va_list} variable and the type of the argument. As another alternative, you can pass the @code{va_list} to another function, which may then use @code{va_arg} to get at the arguments. @code{vprintf} is an example of this. @item Call @code{va_end} to destroy the @code{va_list}. @end itemize 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 @code{NULL}) at the end. Also, the variable arguments will be promoted according to standard C promotion rules. Arguments of type @code{char} and @code{short} will be promoted to @code{int}, and you should retrieve them as such. Those of type @code{float} will be promoted to @code{double}. @subheading Return Value @code{va_arg} returns the argument it fetched, the other macros return nothing. @subheading Portability @portability ansi, posix @subheading Example @example int find_the_sum(int count, @dots{}) @{ 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); @} @end example