Variadic Functions in C
Variadic Functions in C
Variadic Functions in C
Variadic functions are one of the powerful but very rarely used features in C
language. Variadic functions add a lot of flexibility in programming the application
structure.
Variadic Function in C
A function that can take a variable number of arguments is called a variadic function.
One fixed argument is required to define a variadic function.
The most frequently used library functions in C, i.e., printf() and scanf() are in fact
the best-known examples of variadic functions, as we can put a variable number of
arguments after the format specifier string.
You need to include the stdarg.h header file at the top of the code to handle the
variable arguments. This header file provides the following macros to work with the
arguments received by the ellipsis symbol.
Methods Description
va_start(va_list ap, Arguments after the last fixed argument are stored in the
arg) va_list.
https://www.tutorialspoint.com/cprogramming/c_variadic_functions.htm 1/5
6/16/24, 12:28 PM Variadic Functions in C
va_copy(va_list dest,
This creates a copy of the arguments in va_list
va_list src)
The following code uses the concept of a variadic function to return the sum of a
variable number of numeric arguments passed to such a function. The first argument
to the addition() function is the count of the remaining arguments.
va_list args;
va_start (args, n);
Since there are "n" number of arguments that follow, fetch the next argument with
"va_arg()" macro for "n" number of times and perform cumulative addition −
va_end (args);
#include <stdio.h>
#include <stdarg.h>
https://www.tutorialspoint.com/cprogramming/c_variadic_functions.htm 2/5
6/16/24, 12:28 PM Variadic Functions in C
va_list args;
int i, sum = 0;
va_end (args);
return sum;
}
int main(){
return 0;
}
Output
Sum = 15
You can try providing a different set of numbers as the variadic arguments to the
addition() function.
We can extend the concept of variadic function to find the largest number in a given
list of variable number of values.
#include <stdio.h>
#include <stdarg.h>
https://www.tutorialspoint.com/cprogramming/c_variadic_functions.htm 3/5
6/16/24, 12:28 PM Variadic Functions in C
va_end (args);
return max;
}
int main(){
printf("Largest number in the list = %d ", largest(5, 12, 34, 21, 45, 32));
return 0;
}
Output
When you run this code, it will produce the following output −
In the following code, we pass multiple strings to a variadic function that returns a
concatenated string.
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
https://www.tutorialspoint.com/cprogramming/c_variadic_functions.htm 4/5
6/16/24, 12:28 PM Variadic Functions in C
strcpy(string, "");
va_end (args);
return string;
}
int main(){
return 0;
}
Output
Hello World
How are you?
https://www.tutorialspoint.com/cprogramming/c_variadic_functions.htm 5/5