C/C++ language supports variable argument function or variadic function. The prototype defines a single defined argument along with "..." (three dots) to indicate it as Variadic function. Printf and scanf library functions are the best examples of variadic functions.
Variadic functions can take a variable number of arguments and they are optional by nature.
Variadic functions should have at least one argument and after that "..." should be added to indicate that this function takes variable arguments.
Variadic types & macros
Variadic arguments are managed with the help of list and macros and these are defined in header file
- va_list (type) - Main type used in Variadic function, holds the information needed by macros va_start, va_arg, va_end, and va_copy.
- va_start (macro) - takes the fixed argument as input and starts of iterations in the variadic function arguments
- va_arg (macro) - obtain the current variadic function argument, and advances to the next location in stack
- va_copy (macro) - makes a copy of the variadic function arguments (Available only in C99)
- va_end (macro) - ends of iteration in the variadic function arguments, used at the end of the iteration.
Variadic function example
This is one simple example of Variadic function demonstrating how printf/scanf function works.
Variadic functions output
Variadic function example 2
This is another simple example of Variadic function for calculating average of numbers.
Variadic functions output
Variadic function and arguments
Arguments are pushed in the stack from right to left one by one. Each argument takes a size of integer in stack. For data types whose sizes are greater than integer, double or multiples of integer size are taken.
Inside the function, we take the va_list and initialize with the first argument. va_start() macro takes the address of the first argument and advances itself to the next argument. Now with each iteration we call va_arg() which actually returns the value of the current type and the pointer to the next argument. In this way we get the value of each argument and the va_list pointer advances to the next argument.
About our authors: Team EQA
You have viewed 1 page out of 248. Your C learning is 0.00% complete. Login to check your learning progress.
Questions index C Questions C++ Questions Win32 MFC COM/DCOM DLL Questions
Compilers & Editors
Download Visual Studio Download XCode Download Visual Studio Code Android studio install sdk Eclipse installer Best C compilers IDEs
Development system setup
Windows media creation tool MSDN subscription Ubuntu virtualbox
New updated posts
Why learn C? Draw on printer Free alt softwares