C Library Macro -va_end()
C Standard Library - <stdarg.h>
va_endThe macro is in the C standard library<stdarg.h>a macro in the header file, used to clean upva_listvariable, and make it no longer point to any valid memory location. It is used at the end of a variadic function to terminate the handling of variadic arguments.
C Library Macrovoid va_end(va_list ap)Allows usingva_startThe macro returns from a function with variadic arguments. If it is not called before returning from the function...va_end, then the result is undefined.
Declaration
Below is the declaration of the va_end() macro.
void va_end(va_list ap);
Parameter
va_list ap: This is ava_listvariables of the type that have already been passed throughva_startorva_copyThe macro initializes, and is used to access the variable argument list.
Return Value
This macro does not return any value.
Usage steps
- In a variadic function, use the
va_startMacro initializationva_listvariable. - Usage
va_argmacro to retrieve each variadic argument in sequence. - After processing all variadic arguments, use the
va_endMacro cleanupva_listvariable.
Example
The following is an example of usingva_endAn example program of the macro, which defines a variadic function to calculate the sum of a variable number of arguments:
Example
#include <stdarg.h>
// Variadic function, calculates the sum of arguments
int sum(int count, ...) {
int total = 0;
va_list args;
// Initialize args to access variadic arguments
va_start(args, count);
// Get each variadic argument one by one and add 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 us compile and run the above program. This 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 typeargs, which is used to store information about the variable argument list.va_start(args, count);: initializeargsto access fromcountthe variadic arguments that start after that.total += va_arg(args, int);: Useva_argThe macro obtains the next variadic argument, assuming here that they are all...inttype, and accumulate it into thetotalin the variable.va_end(args);: clean upargs, in order to release resources and avoid undefined behavior.
Notes
- Each time you use
va_startInitializeva_listafter the variable, you must useva_endClean it up. va_endThe macro is used to clean upva_listvariable, so as to release any resources and avoid potential memory problems before returning from the function.- Call
va_endAfter,va_listThe variable will no longer be valid and should not be used again.