C Library Macros - va_end()
va_end The macro is a macro in the C standard library a macro in the va_list variable and make it no longer point to any valid memory location. It is used at the end of a variadic function to finish processing the variadic arguments.
C Library Macros void va_end(va_list ap) allows a function with variadic arguments that used the va_start macro to return. If the macro is not called before returning from the function, va_endthe result is undefined.
Declaration
The following is the declaration of the va_end() macro.
void va_end(va_list ap);
Parameters
va_list ap: This is ava_listvariable that has beenva_startorva_copymacro, used to access the variadic argument list.
Return Value
This macro does not return any value.
Usage steps
- In a variadic function, use the
va_startmacro to initializeva_listvariable. - Use
va_argmacro to obtain each variadic argument in turn. - After processing all variadic arguments, use the
va_endmacro cleanupva_listvariable.
Example
The following is an example of using va_end 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
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
- Each time the
va_startInitializationva_listvariable is used, theva_endmust be used to clean it up. va_endThe macro is used to clean up theva_listvariable so that any resources are released and potential memory problems avoided before the function returns.- called
va_endAfter,va_listvariable is no longer valid and should not be used again.
C Standard Library -