stdarg.h
va_arg, va_end, va_start
- Header
- stdarg.h
- Prototype
- type va_arg(va_list arg_ptr, type);
void va_end(va_list arg_ptr);
void va_start(va_list arg_ptr, prev_parm); - Description
These functions maintain a list of arguments to be accessed within functions that accept a variable number of arguments (for example the vprintf function). va_list is a type of variable argument list defined in stdarg.h. Variable argument lists can be processed by a function when it does not know the number of arguments being passed. The va_list array holds information required by va_arg and va_end. When a called function takes a variable argument list, it declares the last parameter of type va_list.
va_start is first called to initialize the argument list, for which the parameter arg_ptr points to the first argument in the va_list. The other parameter prev_parm is the parameter preceding the first argument. After a call to va_start, a call to va_arg will evaluate data type from the location pointed to by arg_ptr and increment arg_ptr. va_end resets arg_ptr to NULL.
- Return Value
- va_arg returns the current argument. va_start and va_end evaluate to void.
- Compatibility
- DOS Windows 3.x Phar Lap DOSX Win32
- Example
/* Example for va_arg, va_end, va_start */ #include <stdlib.h> #include <stdio.h> #include <stdarg.h> void miniprintf(char *formatstr, ...) { va_list marker; int pos = 0; va_start(marker, formatstr); while (formatstr[pos]) { if (formatstr[pos] == '%') { pos++; switch (formatstr[pos]) { case 'S' : case 's' : printf("%s", va_arg(marker,char *)); break; case 'I' : case 'i' : printf("%d", va_arg(marker,int)); } } else putchar(formatstr[pos]); pos++; } va_end(marker); } void main() { miniprintf("This is a string: \"%s\"\nAnd this is an int: (%i)\n", "String", 12); }
- Output
This is a string: "String" And this is an int: (12)