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

C Library Macros – va_arg()

C Library Macros - va_arg()

C Standard Library - <stdarg.h> C Standard Library -

va_arg The macro is a macro in the C standard library header used to successively obtain the value of each variadic argument in a variadic function. It is used after the va_start macro has initialized the va_list variable, to access the next argument in the variable argument list.

Declaration

The following is the declaration of the va_arg() macro.



type va_arg(va_list ap, type);

Parameters

Return Value

Returns the next argument in the current variadic argument list, of type type.

Usage steps

Example

The following is an example of using va_arg a sample program for the macro that defines a variadic function to compute the sum of a variable number of arguments:

Example

#include

#include

// Variadic function that computes the sum of its arguments

int

sum

(

int

count

,

...

)

{

   

int

total

=

0

;

    va_list args

;

   

// Initialize args to access the variadic arguments

   

va_start

(

args

,

count

)

;

   

// Retrieve each variadic argument in turn and add it to total

   

for

(

int

i

=

0

;

i

<

count

;

i

++

)

{

        total

+=

va_arg

(

args

,

int

)

;

   

}

   

// Clean up args

   

va_end

(

args

)

;

   

return

total

;

}

int

main

(

)

{

   

printf

(

"Sum of 1, 2, 3: %d\n"

,

sum

(

3

,

1

,

2

,

3

)

)

;

 

// Output 6

   

printf

(

"Sum of 4, 5, 6, 7: %d\n"

,

sum

(

4

,

4

,

5

,

6

,

7

)

)

;

 

// Output: 22

   

return

0

;

}

Let's compile and run the above program, which will produce the following result:



Sum of 1, 2, 3: 6

Sum of 4, 5, 6, 7: 22

Parsing

Notes

C Standard Library - <stdarg.h> C Standard Library -