Node:Variadic functions, Next:, Previous:Actual parameters and formal parameters, Up:Parameters



Variadic functions

Suppose you are writing a program that repeatedly generates lists of numbers that can run anywhere from one to fifty items. You never know how many numbers a particular list will contain, but you always want to add all the numbers together. Passing them to an ordinary C function will not work, because an ordinary function has a fixed number of formal parameters, and cannot accept an arbitrarily long list of actual parameters. What should you do?

One way of solving this problem is to use a variadic function, or function that can accept arbitrarily long lists of actual parameters. You can do this by including the stdarg.h header in your program. For example, with stdarg.h, you can write a function called add_all that will add all integers passed to it, returning correct results for all of the following calls:

sum = add_all (2, 3, 4);

sum = add_all (10, 150, 9, 81, 14, 2, 2, 31);

sum = add_all (4);

Unfortunately, the use of stdarg.h is beyond the scope of this tutorial. For more information on variadic functions, see the GNU C Library manual.