C Standard Library -<stdarg.h>

<stdarg.h>is a header file in the C standard library, providing a set of macros for accessing a variable number of arguments.

stdarg.hThe header file defines a variable typeva_listand three macros, which can be used to obtain the arguments in a function when the number of arguments is unknown (i.e., the number of arguments is variable).

Functions with variable arguments usually use an ellipsis at the end of the parameter list....defined.

Library variables

The following are the variable types defined in the header file stdarg.h:

Serial NumberVariables & Description
1va_list
This is applicable tova_start()、va_arg()andva_end()The type in which these three macros store information. The type used to store variable argument information.

Library macros

The following are the macros defined in the header file stdarg.h:

Serial NumberMacros & Description
1void va_start(va_list ap, last_arg)
This macro initializesapvariable, whichva_argandva_endThe macros are used together.last_argis the last known fixed parameter passed to the function, i.e., the parameter before the ellipsis.
2type va_arg(va_list ap, type)
This macro retrieves an argument of typetypethe next parameter.
3void va_end(va_list ap)
This macro is now available for useva_startA function with variable arguments returns via the macro. If it is not called before returning from the functionva_end, the result is undefined.

Example

The following is an example using<stdarg.h>An example of implementing a variadic function. This function calculates the sum of all parameters:

Example

#include <stdio.h>
#include <stdarg.h>

// Calculate the sum of variable arguments
int sum(int count, ...) {
    int total = 0;
    va_list args;
   
    // Initialize args to access variadic arguments
    va_start(args, count);
   
    // Access 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:

Sum of 1, 2, 3: 6
Sum of 4, 5, 6, 7: 22

Parsing

  • va_list args;: declare ava_listVariable, used to access variadic arguments.
  • va_start(args, count);: initializeargsTo traverse the variadic argument list, starting fromcountThe first parameter after that.
  • total += va_arg(args, int);: Get the next parameter in the variable argument list and accumulate it tototal. The parameter type isint。
  • va_end(args);: clean upargs。

Notes

  • The type of each argument in the variable argument list must be explicit and must be passed consistently tova_arg。
  • Usageva_startAfter, must useva_endcleanupva_listvariable.
  • va_start、va_argandva_endThe macros should be used in pairs within a function to avoid undefined behavior.
other extensions