|
|
coherent
variable arguments Overview variable arguments
The ANSI Standard mandates the creation of a set of routines to
help implement functions, such as pprriinnttff and ssccaannff, that take a
variable number of arguments. These routines are called from
within another function to help it handle its arguments.
These routines are declared or defined in the header ssttddaarrgg.hh,
and are as follows:
vvaa_aarrgg() Return pointer to next argument in argument list
vvaa_eenndd() Tidy up after an argument list has been traversed
vvaa_ssttaarrtt()Initialize object that holds function arguments
vvaa_aarrgg and vvaa_ssttaarrtt must be implemented as macros; vvaa_eenndd must be
implemented as a library function. All three use the special
type vvaa_lliisstt, which is an object that holds the arguments to the
function being implemented.
***** Example *****
The following example concatenates multiple strings into a common
allocated string and returns the string's address.
#include <stdarg.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
char *
multcat(numargs)
int numargs;
{
va_list argptr;
char *result;
int i, siz;
/* get size required */
va_start(argptr, numargs);
for(siz = i = 0; i < numargs; i++)
siz += strlen(va_arg(argptr, char *));
if ((result = calloc(siz + 1, 1)) == NULL) {
fprintf(stderr, "Out of space\n");
exit(EXIT_FAILURE);
}
va_end(argptr);
COHERENT Lexicon Page 1
variable arguments Overview variable arguments
va_start(argptr, numargs);
for(i = 0; i < numargs; i++)
strcat(result, va_arg(argptr, char *));
va_end(argptr);
return(result);
}
int
main(void)
{
printf(multcat(5, "One ", "two ", "three ",
"testing", ".\n"));
}
***** See Also *****
lliibbrraarriieess, ssttddaarrgg.hh
COHERENT Lexicon Page 2
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.