C Standard Library -
is a header file in the C Standard Library that provides a set of macros for accessing a variable number of arguments.
stdarg.h The header file defines a variable type va_list and three macros that can be used to retrieve arguments from a function when the number of arguments is unknown (i.e., variable).
Functions with variable arguments are generally defined using an ellipsis ... at the end of the parameter list.
Library variables
The variable types defined in the header file stdarg.h are listed below:
| No. | Variable & Description |
|---|---|
| 1 | **va_list ** |
| This is a type suitable for va_start(), va_arg() and va_end() the information stored by these three macros. A type used to store information about variable arguments. |
Library macros
The macros defined in the header file stdarg.h are listed below:
| No. | Macro & description |
|---|---|
| 1 | void va_start(va_list ap, last_arg) |
| This macro initializes 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. | |
| 2 | type va_arg(va_list ap, type) |
| This macro retrieves the next argument of type type in the function's argument list. | |
| 3 | void va_end(va_list ap) |
| This macro allows the use of va_start macro to return. If the macro is not called before returning from the function, va_endthe result is undefined. |
Example
The following is an example of using An example of implementing a variadic function. This function computes the sum of all its arguments:
Example
#include
#include
// Calculate the sum of the variable arguments
int
sum
(
int
count
,
...
)
{
int
total
=
0
;
va_list args
;
// Initialize args to access the variadic arguments
va_start
(
args
,
count
)
;
// Access the variable arguments one by one
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
;
}
Output result:
Sum of 1, 2, 3: 6
Sum of 4, 5, 6, 7: 22
Parsing
va_list args;: declare ava_listvariable used to access the variable arguments.va_start(args, count);: initializeargsto traverse the variable argument list, starting fromcountthe first unnamed argument.total += va_arg(args, int);: Retrieve the next argument from the variable argument list and add it tototalthe running total. The argument type isint.va_end(args);: clean upargs.
Notes
- The type of each argument in the variable argument list must be clear and must be passed consistently to
va_arg. - Use
va_startAfter retrieving arguments, you must useva_endClean upva_listvariable. va_start,va_argandva_endva_end to clean up; these macros should be used in pairs within a function to avoid undefined behavior.