h-stdarg
Table of Contents
<stdarg.h>
<stdarg.h> provides va_list, va_start(), va_arg(), and va_end() for implementing variadic functions accepting a variable number of arguments. The caller must ensure type safety—there's no runtime checking that passed arguments match what the function expects.
Use an explicit count or sentinel value to bound the argument list.
Example
This example implements a variadic function that finds the minimum of integers.
// compile: gcc -o stdargexample stdargexample.c // run: ./stdargexample // description: variadic minimum function #include <stdarg.h> #include <limits.h> #include <stdio.h> int vmin(int count, ...) { va_list args; va_start(args, count); int result = INT_MAX; for (int i = 0; i < count; i++) { int v = va_arg(args, int); if (v < result) result = v; } va_end(args); return result; } int main() { printf("min(3, 7, 1, 9) = %d\n", vmin(4, 3, 7, 1, 9)); return 0; }
Common types and macros
va_list: type for argument list pointerva_start(ap, last): initialize argument list (last is param before...)va_arg(ap, type): get next argumentva_end(ap): clean up argument listva_copy(dest, src): copy argument list (C99)printf("min(42) = %d\n", vmin(1, 42)); return 0;} ```
h-stdarg.md · Last modified: by 127.0.0.1
