Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Variadic Functions

C Variadic Functions

Sometimes you may encounter a situation where you want a function to take a variable number of arguments rather than a predefined number.

C provides a solution for this situation: it allows you to define a function that can accept a variable number of arguments according to specific needs.

The declaration is as follows:

int func_name(int arg1, ...);

Here, the ellipsis ... represents the variable argument list.

The following example demonstrates the use of such a function:

int

func

(

int

, ...

)

{

. . .

}

int

main

(

)

{

func

(

2

,

2

,

3

)

;

func

(

3

,

2

,

3

,

4

)

;

}

Note that the function func() has its last argument written as an ellipsis, namely three dots (...), and the argument before the ellipsis is int, representing the total number of variable arguments to be passed. To use this feature, you need to use the stdarg.h header file, which provides the functions and macros for implementing variadic functionality. The specific steps are as follows:

The commonly used macros are:

Now, following the steps above, let's write a function with a variable number of arguments that returns their average:

Example

#include

<

stdio.h

#include

<

stdarg.h

double

average

(

int

num

,...

)

{

va_list

valist

;

double

sum

=

0

.0

;

int

i

;

/*

Initialize valist for num arguments

*/

va_start

(

valist

,

num

)

;

/*

Access all arguments assigned to valist

*/

for

(

i

=

0

;

i

<

num

;

i

++

)

{

sum

+=

va_arg

(

valist

,

int

)

;

}

/*

Clean up the memory reserved for valist

*/

va_end

(

valist

)

;

return

sum

/

num

;

}

int

main

(

)

{

printf

(

"

Average of 2, 3, 4, 5 = %f

\

n

"

,

average

(

4

,

2

,

3

,

4

,

5

)

)

;

printf

(

"

Average of 5, 10, 15 = %f

\

n

"

,

average

(

3

,

5

,

10

,

15

)

)

;

}

In the example above, the average() function takes an integer num and any number of integer arguments. Inside the function, a variable of type va_list is used to access the variable argument list. In the loop, the va_arg() macro is used each time to obtain the next integer argument and print it. Finally, the va_end() macro is used at the end of the function to finish accessing the variable argument list.

When the code above is compiled and executed, it produces the following result. It should be noted that the function **average()** is called twice, and each time the first argument indicates the total number of variable arguments passed. The ellipsis is used to pass a variable number of arguments.



Average of 2, 3, 4, 5 = 3.500000

Average of 5, 10, 15 = 10.000000