0Pricing
C Academy · Lesson

The stdarg Macros

va_list, va_start, va_arg.

What are variadic functions?

A variadic function accepts a variable number of arguments. You have used one already: printf can take any number of values.

C lets you write your own using the <stdarg.h> macros.

#include <stdio.h>

int main(void) {
    printf("%d %d %d\n", 1, 2, 3);
    printf("%s\n", "any count of args");
    return 0;
}

The ellipsis

You declare a variadic function with ... (the ellipsis) as the last parameter.

At least one named parameter must come before it, so the function knows where the variable part begins.

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

void demo(int count, ...) {
    printf("This function takes %d extra args\n", count);
}

int main(void) {
    demo(3, 10, 20, 30);
    return 0;
}

All lessons in this course

  1. The stdarg Macros
  2. Writing printf-like Functions
  3. Type Safety Concerns
  4. Practical Examples
← Back to C Academy