C Library Macros - va_start()
Description
va_start The macro is a macro in the C standard library a macro in the 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
va_list ap: a type used to access variadic arguments. It will be initialized after the macro call for use in subsequentva_argcalls to retrieve arguments.last: the last known fixed argument before the variadic argument list, i.e., the last parameter in the function's parameter list before the variadic arguments begin.
Return Value
NA
Usage steps
- To define a variadic function, there must be at least one fixed parameter (i.e., the
lastparameter). - declare a
va_listvariable to store information about the variadic argument list. - Use
va_startmacro to initializeva_listvariable. - Use
va_argmacro to obtain each variadic argument in turn. - Use
va_endmacro cleanupva_listvariable.
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
va_list args;: declare ava_listvariable of typeargsto store information about the variadic argument list.va_start(args, count);: initializeargsto access the variadic arguments that begin aftercountthe last named argument.total += va_arg(args, int);: When usingva_argmacro retrieves the next variadic argument, assuming they are all of typeint, and adds it tototalvariable.va_end(args);: clean upargsto release resources and avoid undefined behavior.
Notes
va_startIt must be used together withva_list,va_argandva_end.- called
va_startAfter it, you must callva_endto end the processing of variadic arguments. - When calling
va_startBefore that, make sure the function's parameter list has at least one fixed parameter. lastThe parameter is the last fixed argument before the variadic argument list, used to determine where to start processing the variadic arguments.
C Standard Library -