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

C Library Macros – va_start()

C Library Macros - va_start()

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

Description

va_start The macro is a macro in the C standard library a macro in the header used to initialize a va_list variable so that a variable number of arguments can be accessed in a variadic function.

C Library Macros void va_start(va_list ap, last_arg) Initialization ap variable, which is used together with the va_arg and va_end macro.last_arg is the last known fixed argument passed to the function, i.e., the argument before the ellipsis.

This macro must be used before using va_arg and va_end .

Declaration

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



void va_start(va_list ap, last);

Parameters

Return Value

NA

Usage steps

  1. To define a variadic function, there must be at least one fixed parameter (i.e., the last parameter).
  2. declare a va_list variable to store information about the variadic argument list.
  3. Use va_start macro to initialize va_list variable.
  4. Use va_arg macro to obtain each variadic argument in turn.
  5. Use va_end macro cleanup va_list variable.

Example

The following example demonstrates the use of the va_start() macro.

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 -