Variable parameter lists are implemented by macros that are defined in the Stdarg.h header file and are part of the standard library, which declares a type va_list and three macros Va_start,va_arg and Va_end
Declares the va_list type variable arg, which is used to access the indeterminate part of the parameter list, initialized with Va_start, whose first argument is the variable name of Va_list, and the second is the last named argument before the ellipsis. Initialize the arg variable to the first parameter that points to the variable parameter section
Va_arg, accepts two parameters, va_list the variable and the type of the next parameter in the argument list. Return the parameter value and point to the next mutable parameter
Va_end called after accessing the last mutable parameter
Averaging #include<stdio.h> #include <stdlib.h> #include <stdarg.h>int my_average (int count, ...) {va_list arg;//char* type int sum = 0;va_start (arg, count); int i = 0;for (i = 0; i < count; i++) {sum + = Va_arg (ARG, int.);// Gets an reshape variable}va_end (ARG) backwards; return sum/count;} int main () {int avg = my_average (3, 7, 2, 3);p rintf ("%d\n", avg); System ("pause"); return 0;}
Example Two
Max #include<stdio.h> #include <stdlib.h> #include <stdarg.h>int my_max (int n, ...) {va_list Arg;va_start (ARG, n); int max = 0;int I=0;max = va_arg (arg, int); for (i = 1; i < n; i++) {int tmp = VA_ARG (ARG, int), if (Max < tmp) {max = tmp;}} Va_end (ARG); return Max;} int main () {int ret = My_max (3, 2, -4, 1);p rintf ("%d", ret); System ("pause"); return 0;}
This article is from the "incomparable Warm yang" blog, please be sure to keep this source http://10797127.blog.51cto.com/10787127/1716926
Variable parameter list