Have you noticed something special about printf()?
printf("Hello\n");
printf("%d\n", age);
printf("%s is %d years old\n", name, age);
The same function accepts one argument, two arguments, or three. The functions we wrote in the Functions topic always had a fixed number of parameters. So how does printf() do it?
The answer is that printf() is a variadic function, and C lets us write our own.
What is a Variadic Function?
A variadic function is a function that can accept a variable number of arguments.
It is declared with an ellipsis (...) at the end of its parameter list:
int sum(int count, ...);
Here:
countis a normal, named parameter....means "zero or more extra arguments of any type may follow".
Well-known variadic functions from the standard library include printf(), scanf(), fprintf() and sprintf().
The <stdarg.h> Header
The extra arguments have no names, so we cannot access them like normal parameters. Instead we use a special type and a set of macros from <stdarg.h>:
Name | What it does |
|---|---|
| A type that keeps track of which extra argument comes next |
| Initializes |
| Returns the next extra argument, treating it as |
| Cleans up; must be called before the function returns |
| Makes a copy of a |
The "va" stands for variable arguments.
Every variadic function follows the same four steps:
1. Declare va_list args;
↓
2. Start va_start(args, lastNamedParameter);
↓
3. Read va_arg(args, type); ← repeat once per argument
↓
4. End va_end(args);
You can picture va_list as a reading finger that moves along the extra arguments:
sum(3, 10, 20, 30)
| ^
count |
va_start puts the finger here
each va_arg(args, int) reads one value and moves the finger right:
1st call → 10, 2nd call → 20, 3rd call → 30
Example: Sum of Any Number of Integers
#include <stdio.h>
#include <stdarg.h>
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;
}
int main()
{
printf("%d\n", sum(3, 10, 20, 30));
printf("%d\n", sum(5, 1, 2, 3, 4, 5));
printf("%d\n", sum(0));
return 0;
}
Output:
60
15
0
The first argument tells the function how many extra arguments follow. This is important, because a variadic function has no built-in way to know how many arguments were passed or what their types are.
How Does the Function Know When to Stop?
Since C does not tell the function the number or types of the extra arguments, the caller must provide that information somehow. There are three common techniques:
Technique | How it works | Example |
|---|---|---|
Count argument | A named parameter says how many values follow |
|
Sentinel value | A special value marks the end of the list |
|
Format string | A string describes the number and types of arguments |
|
Using a Sentinel
Here, the list of strings ends when the function sees NULL:
#include <stdio.h>
#include <stdarg.h>
void printWords(const char *first, ...)
{
va_list args;
const char *word = first;
va_start(args, first);
while (word != NULL)
{
printf("%s", word);
word = va_arg(args, char *);
if (word != NULL)
{
printf(" ");
}
}
printf("\n");
va_end(args);
}
int main()
{
printWords("C", "is", "fun", (char *)NULL);
printWords("Hello", (char *)NULL);
return 0;
}
Output:
C is fun
Hello
Why (char *)NULL instead of just NULL? NULL is allowed to be defined as a plain 0, which is an int. In a variadic call, nothing converts it to a pointer, so on a 64-bit system a 4-byte int may be passed where the function reads an 8-byte pointer. Casting makes the sentinel a real pointer.
Using a Format String
This is how printf() works internally. Let's build a tiny version where each letter describes the type of the next argument:
#include <stdio.h>
#include <stdarg.h>
/* d = int, c = char, f = double, s = string */
void miniPrint(const char *types, ...)
{
va_list args;
va_start(args, types);
for (int i = 0; types[i] != '\0'; i++)
{
switch (types[i])
{
case 'd':
printf("int: %d\n", va_arg(args, int));
break;
case 'c':
/* char is promoted to int, so read an int */
printf("char: %c\n", va_arg(args, int));
break;
case 'f':
/* float is promoted to double, so read a double */
printf("double: %.2f\n", va_arg(args, double));
break;
case 's':
printf("string: %s\n", va_arg(args, char *));
break;
}
}
va_end(args);
}
int main()
{
miniPrint("dcfs", 42, 'A', 3.14, "placement");
return 0;
}
Output:
int: 42
char: A
double: 3.14
string: placement
Notice that the 'c' case reads an int, not a char. The next section explains why.
Default Argument Promotions
When values are passed through ..., C automatically applies the default argument promotions:
Type you pass | Type actually received | So read it with |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
| Unchanged | The same type |
So never write va_arg(args, char), va_arg(args, short) or va_arg(args, float). The argument was already converted, and reading it with the wrong type is undefined behavior.
This also explains a classic interview question: why does printf() use %f for both float and double, while scanf() needs %f for float and %lf for double? Because a float passed to printf() is promoted to double, so printf() always receives a double. But scanf() receives pointers (float * or double *), and pointers are not promoted, so it must know exactly which one it got.
Example: Average of double Values
#include <stdio.h>
#include <stdarg.h>
double average(int count, ...)
{
va_list args;
double total = 0.0;
va_start(args, count);
for (int i = 0; i < count; i++)
{
total += va_arg(args, double);
}
va_end(args);
return count > 0 ? total / count : 0.0;
}
int main()
{
float f = 2.5f;
printf("%.2f\n", average(3, 1.5, 2.5, 4.0));
printf("%.2f\n", average(2, f, 3.5)); /* float is promoted to double */
printf("%.2f\n", average(2, 10.0, 20.0));
return 0;
}
Output:
2.67
3.00
15.00
Careful: calling average(2, 10, 20) would be a bug. 10 and 20 are int values, and int is not converted to double in a variadic call. The function would read them as double, which is undefined behavior and usually prints garbage. Always write 10.0 or cast with (double).
Passing the Arguments On: vprintf()
A very common real-world use of variadic functions is a logging function that adds something extra and then forwards the rest to printf().
We cannot pass ... directly to another function. Instead, the standard library provides versions of the print functions that take a va_list: vprintf(), vfprintf(), vsprintf() and vsnprintf().
#include <stdio.h>
#include <stdarg.h>
void logMessage(const char *level, const char *format, ...)
{
va_list args;
printf("[%s] ", level);
va_start(args, format);
vprintf(format, args);
va_end(args);
printf("\n");
}
int main()
{
int marks = 87;
const char *name = "Asha";
logMessage("INFO", "Program started");
logMessage("INFO", "%s scored %d marks", name, marks);
logMessage("WARN", "Only %d%% memory left", 15);
return 0;
}
Output:
[INFO] Program started
[INFO] Asha scored 87 marks
[WARN] Only 15% memory left
Note that va_start uses format, because it is the last named parameter before ....
Reading the Arguments Twice: va_copy
Once va_arg has moved past an argument, it cannot go back. If you need to go through the arguments twice, make a copy with va_copy first:
#include <stdio.h>
#include <stdarg.h>
void printTwice(int count, ...)
{
va_list args, copy;
va_start(args, count);
va_copy(copy, args);
printf("Values:");
for (int i = 0; i < count; i++)
printf(" %d", va_arg(args, int));
printf("\n");
printf("Times 10:");
for (int i = 0; i < count; i++)
printf(" %d", va_arg(copy, int) * 10);
printf("\n");
va_end(copy);
va_end(args);
}
int main()
{
printTwice(3, 1, 2, 3);
return 0;
}
Output:
Values: 1 2 3
Times 10: 10 20 30
Every va_copy needs its own matching va_end. Do not simply assign one va_list to another with =; on some platforms va_list is an array type and that will not work.
Variadic Macros
In the Preprocessor Directives topic we wrote macros with a fixed number of parameters. Since C99, macros can also be variadic. The extra arguments are available through __VA_ARGS__:
#include <stdio.h>
#define LOG(format, ...) printf("[LOG] " format "\n", __VA_ARGS__)
int main()
{
int x = 5, y = 7;
LOG("x = %d, y = %d", x, y);
LOG("sum = %d", x + y);
return 0;
}
Output:
[LOG] x = 5, y = 7
[LOG] sum = 12
Here "[LOG] " format "\n" works because adjacent string literals are joined into one string. With this simple version, at least one argument must follow the format string; C23 added __VA_OPT__ to handle the "no extra arguments" case cleanly.
Rules to Remember
Before C23, a variadic function must have at least one named parameter before
..., and that last named parameter is passed tova_start. C23 relaxed this:void f(...)is now allowed andva_start(args)may be called with just theva_list. Most code you will see still uses the older form.The
...must be the last thing in the parameter list.Every
va_start(andva_copy) must be matched by ava_endin the same function.A variadic function must be declared with a prototype (for example, through a header) before it is called. Calling it without a visible prototype is undefined behavior.
The compiler does not check the types of the extra arguments. GCC and Clang check
printf-style calls when-Wallis on, but not your own functions unless you mark them with the non-standard__attribute__((format(printf, 1, 2))).
Common Mistakes
Reading more arguments than were passed. For example,
sum(5, 1, 2)makes the function read three values that do not exist. This is undefined behavior; there is no error message.Reading with the wrong type.
va_arg(args, double)on anintargument, orva_arg(args, int)on adouble, gives garbage or worse.Using
char,shortorfloatinva_arg. Useintanddoublebecause of the default argument promotions.Passing
NULLas a pointer sentinel without a cast. Use(char *)NULLor the right pointer type.Forgetting
va_end, especially on an earlyreturn.Passing a user string as the format, for example
printf(userInput). If the input contains%characters,printf()will read arguments that were never passed. Always writeprintf("%s", userInput).
Fixed vs Variadic Functions
Point | Fixed-Parameter Function | Variadic Function |
|---|---|---|
Number of arguments | Always the same | Can change from call to call |
Type checking | Compiler checks every argument | No checking for the extra arguments |
Argument conversion | Converted to the parameter type | Only default promotions ( |
Accessing arguments | By parameter name | Through |
Safety | Safer | Easy to misuse |
Examples |
|
|
Because they are less safe, use variadic functions only when the number of arguments truly varies. If all values have the same type, passing an array and its length is often a simpler and safer choice.
Interview Tips
"How does
printf()accept any number of arguments?" It is declared asint printf(const char *format, ...);and uses<stdarg.h>. The format string tells it how many arguments to read and of which type."What happens if
printf("%d %d", 5)is called?" It is undefined behavior.printf()tries to read a second argument that was never passed, and often prints a garbage value."Can a variadic function find out how many arguments it received?" No. The caller must supply a count, a sentinel, or a format string.
"Why is
va_arg(ap, float)wrong?" Because afloatargument is promoted todouble.Know the four macros in order:
va_start→va_arg→va_end, plusva_copy.
In Simple Words
A variadic function uses
...to accept a variable number of arguments, and reads them one by one using the macros from<stdarg.h>.
Remember:
... → "more arguments may follow"
va_list args; → declare the argument tracker
va_start → begin after the last named parameter
va_arg → read the next argument (as int, double, pointer...)
va_end → finish and clean up
The function must be told how many arguments there are and what types they have, through a count, a sentinel, or a format string. Get this wrong, and the result is undefined behavior.