Skip to content
StudyFame

Variadic Functions in C

You call printf with one argument, three arguments or ten, and it works every time. How? printf is a variadic function: a function that accepts a variable number of arguments. You can write your own using the header <stdarg.h>.

In this lesson you will learn the ... (ellipsis) syntax, the four macros va_list, va_start, va_arg and va_end, two ways to know how many arguments were passed, and the type rules that cause most bugs.

What You Will Learn

  • What a variadic function is.
  • How to declare one with ....
  • How va_list, va_start, va_arg and va_end read the extra arguments.
  • How the function knows how many arguments it got.
  • Default argument promotions (float → double, char → int).
  • How to write a small printf-like function.

Variadic Functions in C Explained

Exam definition: A variadic function is a function that takes a variable number of arguments. It is declared with at least one fixed parameter followed by an ellipsis (...). The extra arguments are accessed with the macros of <stdarg.h>: va_list (a type to hold the argument list), va_start (initialises it after the last fixed parameter), va_arg (returns the next argument of a given type) and va_end (cleans up).

Memory trick: Reading variable arguments is like eating from a tiffin box with stacked containers. va_list is the tiffin, va_start opens the lid, va_arg takes out the next container (you must know what food type is inside!), and va_end closes the tiffin. Nobody tells you how many containers there are, so the first fixed argument must say so.

Syntax of a Variadic Function

#include <stdarg.h>

return_type name(type fixed_param, ...)   /* at least one fixed parameter */
{
    va_list args;                  /* 1. declare the list             */
    va_start(args, fixed_param);   /* 2. start after the last fixed one */

    type value = va_arg(args, type);  /* 3. read the next argument     */
    /* ... repeat va_arg as many times as needed ...                    */

    va_end(args);                  /* 4. always clean up              */
}
Macro / typeJob
va_listType of the variable that walks through the extra arguments
va_start(ap, last)Points ap at the first extra argument; last is the last fixed parameter
va_arg(ap, type)Returns the next argument as type and moves forward
va_end(ap)Finishes; must be called before the function returns
va_copy(dest, src)Copies a list, to read the arguments twice (C99)

Example 1: Sum of Any Number of Integers

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

int sum(int count, ...)
{
    va_list args;
    int i, total = 0;

    va_start(args, count);
    for (i = 0; i < count; i++)
        total += va_arg(args, int);
    va_end(args);

    return total;
}

int main(void)
{
    printf("sum(3, 10, 20, 30)      = %d\n", sum(3, 10, 20, 30));
    printf("sum(5, 1, 2, 3, 4, 5)   = %d\n", sum(5, 1, 2, 3, 4, 5));
    printf("sum(1, 99)              = %d\n", sum(1, 99));
    printf("sum(0)                  = %d\n", sum(0));
    return 0;
}

Output

sum(3, 10, 20, 30)      = 60
sum(5, 1, 2, 3, 4, 5)   = 15
sum(1, 99)              = 99
sum(0)                  = 0

Code Explanation

  1. int sum(int count, ...): count is the fixed parameter; ... means "any number of further arguments".
  2. va_list args; declares the list reader.
  3. va_start(args, count); starts reading just after count.
  4. va_arg(args, int) returns the next argument as an int. The loop calls it exactly count times.
  5. va_end(args); finishes. Every va_start needs a matching va_end.
  6. The caller tells the function how many numbers follow by passing the count first: sum(3, 10, 20, 30).

How Variadic Functions Work

The function has no built-in way to know how many extra arguments were passed or what their types are. You must give it that information. There are three common designs:

DesignExampleHow it knows when to stop
Count firstsum(3, 10, 20, 30)The first argument is the count
Sentinel at the endsum_until(10, 20, 30, -1)A special value (−1, 0 or NULL) marks the end
Format stringprintf("%d %s", n, s)Each % code says one argument and its type

Default argument promotions: extra arguments are converted before they are passed. char and short become int; float becomes double. So you must read them as va_arg(args, int) and va_arg(args, double), never as char or float.

Example 2: A Mini printf with a Format String

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

/* d = int, f = double, s = string, c = char */
void show(const char *types, ...)
{
    va_list args;
    const char *t;

    va_start(args, types);
    for (t = types; *t != '\0'; t++)
    {
        switch (*t)
        {
        case 'd': printf("int    : %d\n", va_arg(args, int)); break;
        case 'f': printf("double : %.2f\n", va_arg(args, double)); break;
        case 's': printf("string : %s\n", va_arg(args, char *)); break;
        case 'c': printf("char   : %c\n", va_arg(args, int)); break;  /* char was promoted to int */
        }
    }
    va_end(args);
}

int main(void)
{
    float price = 49.5f;

    show("dfsc", 42, price, "StudyFame", 'Z');
    printf("---\n");
    show("sd", "Marks", 87);
    return 0;
}

Output

int    : 42
double : 49.50
string : StudyFame
char   : Z
---
string : Marks
int    : 87
  • The string "dfsc" tells the function how many arguments follow and what type each one is, just like printf's format string.
  • price is a float, but it is promoted to double, so it is read with va_arg(args, double).
  • 'Z' is promoted to int, so it is read with va_arg(args, int).
  • If the types string and the real arguments don't match, the behavior is undefined, which is exactly why printf("%d", 3.5) prints garbage.

Important Points to Remember

  • A variadic function needs at least one fixed parameter before ....
  • Include <stdarg.h>; use va_list → va_start → va_arg → va_end.
  • The function must be told the number and types of arguments (count, sentinel or format).
  • Read promoted types: int for char/short, double for float.
  • Reading more arguments than were passed, or with the wrong type, is undefined behavior.
  • Examples from the library: printf, scanf, fprintf, sprintf.

Common Mistakes Beginners Make

MistakeWhat happensFix
va_arg(args, float)Wrong value (float was promoted to double)Use va_arg(args, double)
va_arg(args, char)Wrong value or warningUse va_arg(args, int)
Wrong count: sum(4, 1, 2, 3)Reads a 4th value that doesn't exist (garbage)Pass the correct count or use a sentinel
Forgetting va_endUndefined behavior on some systemsPair every va_start with va_end
int f(...) with no fixed parameterNot allowed before C23; va_start needs itAdd a fixed parameter such as a count

Variable Arguments Practice Questions

  1. What is a variadic function? Give two library examples.
  2. Name the four main macros/types of stdarg.h and their jobs.
  3. Why does a variadic function need at least one fixed parameter?
  4. Why is a float argument read with va_arg(args, double)?
  5. Name two ways a variadic function can know how many arguments it received.
Show answers
  1. A function that accepts a variable number of arguments; printf and scanf.
  2. va_list (holds the list), va_start (begin after the last fixed parameter), va_arg (get the next argument of a type), va_end (finish).
  3. va_start needs the last fixed parameter to find where the extra arguments begin.
  4. Because of default argument promotions: float is converted to double when passed through ....
  5. A count argument, a sentinel value at the end, or a format string.

Coding Exercise

Write int max_of(int count, ...) that returns the largest of count integers, and double average(int count, ...) that returns the average of count doubles. Test with max_of(5, 12, 45, 7, 33, 21) and average(4, 2.5, 3.5, 4.0, 6.0).

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

int max_of(int count, ...)
{
    va_list args;
    int i, best, value;

    va_start(args, count);
    best = va_arg(args, int);
    for (i = 1; i < count; i++)
    {
        value = va_arg(args, int);
        if (value > best)
            best = value;
    }
    va_end(args);
    return best;
}

double average(int count, ...)
{
    va_list args;
    double total = 0;
    int i;

    va_start(args, count);
    for (i = 0; i < count; i++)
        total += va_arg(args, double);
    va_end(args);
    return total / count;
}

int main(void)
{
    printf("max_of  = %d\n", max_of(5, 12, 45, 7, 33, 21));
    printf("average = %.2f\n", average(4, 2.5, 3.5, 4.0, 6.0));
    return 0;
}
max_of  = 45
average = 4.00

Pass 4.0 and 6.0 as doubles; writing 4 would pass an int, and reading it as a double would be undefined behavior.

Quick Quiz: Variable Arguments (MCQ)

  1. Which header provides va_list and va_arg?

    A) stdio.h   B) stdlib.h   C) stdarg.h   D) string.h

  2. The ellipsis in a function declaration is written as:

    A) ..   B) ...   C) *   D) []

  3. Which macro must be called before returning?

    A) va_start   B) va_arg   C) va_end   D) va_list

  4. A char passed to a variadic function is read as:

    A) char   B) int   C) float   D) long double

  5. Which is a variadic function?

    A) strlen   B) printf   C) sqrt   D) fclose

Show answers
  1. C: stdarg.h.
  2. B: ....
  3. C: va_end.
  4. B: int.
  5. B: printf.

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

Variadic functionTakes a variable number of arguments
DeclarationFixed parameter then ...
Header<stdarg.h>
Orderva_list → va_start → va_arg → va_end
Promotionschar/short → int, float → double
Knowing the countCount, sentinel or format string
Examplesprintf, scanf

Frequently asked questions

How do you write a function with a variable number of arguments in C?
Declare it with a fixed parameter and ..., then read the extras with va_start, va_arg and va_end from stdarg.h.
How does printf know how many arguments it has?
From its format string: each % specifier stands for one argument and its type.
Why can't you use va_arg(ap, float)?
Floats are promoted to double when passed through ..., so they must be read as double.

Remember

  • Tiffin box: open (va_start), take out (va_arg), close (va_end).
  • Always tell the function how many and what type.

Next Topic

Next lesson: Multi-File Programs in C. You will split a program into several .c files and share variables with extern.