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 / type | Job |
|---|---|
va_list | Type 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
int sum(int count, ...):countis the fixed parameter;...means "any number of further arguments".va_list args;declares the list reader.va_start(args, count);starts reading just aftercount.va_arg(args, int)returns the next argument as anint. The loop calls it exactlycounttimes.va_end(args);finishes. Everyva_startneeds a matchingva_end.- 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:
| Design | Example | How it knows when to stop |
|---|---|---|
| Count first | sum(3, 10, 20, 30) | The first argument is the count |
| Sentinel at the end | sum_until(10, 20, 30, -1) | A special value (−1, 0 or NULL) marks the end |
| Format string | printf("%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 likeprintf's format string. priceis afloat, but it is promoted todouble, so it is read withva_arg(args, double).'Z'is promoted toint, so it is read withva_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
| Mistake | What happens | Fix |
|---|---|---|
va_arg(args, float) | Wrong value (float was promoted to double) | Use va_arg(args, double) |
va_arg(args, char) | Wrong value or warning | Use 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_end | Undefined behavior on some systems | Pair every va_start with va_end |
int f(...) with no fixed parameter | Not allowed before C23; va_start needs it | Add a fixed parameter such as a count |
Variable Arguments Practice Questions
- What is a variadic function? Give two library examples.
- Name the four main macros/types of stdarg.h and their jobs.
- Why does a variadic function need at least one fixed parameter?
- Why is a float argument read with
va_arg(args, double)? - Name two ways a variadic function can know how many arguments it received.
Show answers
- A function that accepts a variable number of arguments; printf and scanf.
- 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).
- va_start needs the last fixed parameter to find where the extra arguments begin.
- Because of default argument promotions: float is converted to double when passed through
.... - 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)
-
Which header provides va_list and va_arg?
A) stdio.h B) stdlib.h C) stdarg.h D) string.h
-
The ellipsis in a function declaration is written as:
A)
..B)...C)*D)[] -
Which macro must be called before returning?
A) va_start B) va_arg C) va_end D) va_list
-
A
charpassed to a variadic function is read as:A) char B) int C) float D) long double
-
Which is a variadic function?
A) strlen B) printf C) sqrt D) fclose
Show answers
- C: stdarg.h.
- B:
.... - C: va_end.
- B: int.
- B: printf.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Variadic function | Takes a variable number of arguments |
|---|---|
| Declaration | Fixed parameter then ... |
| Header | <stdarg.h> |
| Order | va_list → va_start → va_arg → va_end |
| Promotions | char/short → int, float → double |
| Knowing the count | Count, sentinel or format string |
| Examples | printf, 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.