Recently looking at <the C programming language> K&r
7.3 Chapter Variable-length Argument Lists variable length parameter list, take a note of usage
1. header files to use <stdarg.h>
Contains some macro (marco) definitions used to traverse (step through) variable-length parameter lists
2. Type Va_list:refer to all argument in turn (VA is the abbreviation for variadic arguments)
Va_list ap; /* Declare va_list type of pointer ap */
3. Macro Va_start
Usage: Va_start (va_list, char *);
Initializes a pointer to the Va_list type, pointing to the first unnamed parameter in the list, and must first call it
Va_start to use the last named argument, so at least one named parameter in the function argument list
4.va_arg
Usage: va_arg (va_list, type name); /* type name may be int double these types */
Returns a parameter that points the pointer to the next parameter
5.va_end
Usage: va_end (va_list);
The aftermath of Va_start's work
6.va_cpy
Usage: va_copy (va_list src, va_list dest);
Sample Code : (Excerpt from: Man page)
Simple sequential invocation of the va_list va_start va_arg va_end
/* The function foo takes a string of format characters and prints out the argument associated
* with all format character based on the type.
*/
#include <stdio.h>#include<stdarg.h>voidFoo (Char*FMT, ...) {va_list ap; intD; CharC, *s; Va_start (AP, FMT); while(*FMT)Switch(*fmt++) { Case 's':/*string*/s= Va_arg (AP,Char*); printf ("string%s\n", s); Break; Case 'D':/*int*/D= Va_arg (AP,int); printf ("int%d\n", D); Break; Case 'C':/*Char*/ /*need a cast here since Va_arg only takes fully promoted types*/C= (Char) Va_arg (AP,int); printf ("Char%c\n", c); Break; } va_end (AP); }
attached : Linux can be used under the Man command to view Stdarg, Va_start, Va_arg, Va_end, va_copy
Mans 3 Stdarg
Use of variadic function