Skip to content

C Variable Arguments

Variable arguments allow functions to accept a variable number of parameters.

1.stdarg.h Header

c
#include <stdarg.h>
#include <stdio.h>

2. Variable Argument Functions

c
int sum(int count, ...) {
    va_list args;
    int total = 0;
    
    va_start(args, count);
    for (int i = 0; i < count; i++) {
        total += va_arg(args, int);
    }
    va_end(args);
    
    return total;
}

3. Using Variable Arguments

c
int result = sum(4, 10, 20, 30, 40);  // result = 100

4. Custom printf Function

c
void my_printf(const char *format, ...) {
    va_list args;
    va_start(args, format);
    vprintf(format, args);
    va_end(args);
}

5. Important Notes

  • At least one named parameter is required
  • Must call va_start and va_end
  • Use va_arg to extract arguments
  • Type safety is the programmer's responsibility

Content is for learning and research only.