A multi-parameter function like printf is implemented using a macro in stdarg. h.
Va_list: A pointer used to define the traversal parameter list. va_start: points the pointer to the first parameter. va_arg: gets the next parameter and moves it backward. va_end: releases the pointer to complete the traversal.
1. Sum of integers:
In this example, the summation of integers in a series must have at least three parameters, and the last one must be 0.
The last 0 is used to identify the end of the list.
# Include <stdio. h> # include <stdarg. h> int sum (INT N1, int N2 ,...) {/* defines a pointer to the parameter list, which must be of the va_list type */va_list P;/* defines the output variable, obtain the first two values */INT out = N1 + N2;/* point the pointer to the last explicit variable */va_start (p, N2 ); /* use va_arg to obtain the next integer. va_arg also moves the pointer back to the position of the integer. * // * in this example, it is assumed that the parameter is an integer and ends with 0; in this case, the last parameter must be 0 */while (n2 = va_arg (p, INT ))! = 0) out + = n2;/* end */va_end (p); Return (out);} int main (void) {printf ("% d \ n ", sum (,);/* 6 */printf ("% d \ n", sum )); /* 45 */getchar (); Return 0 ;}
2. Integer summation (modified version ):
This function requires at least two parameters and must end with 0.
# Include <stdio. h> # include <stdarg. h> int sum (INT N1 ,...) {va_list P; int out = N1; va_start (p, N1); While (n1 = va_arg (p, INT ))! = 0) out + = N1; va_end (p); Return (out);} int main (void) {printf ("% d \ n", sum (2, 0 )); /* 2 */printf ("% d \ n", sum (1, 2, 3, 4, 5, 6, 7, 8, 9, 0);/* 45 */getchar (); return 0 ;}
3. Specify the sum of floating point numbers:
This function parameter specifies a number followed by a list.
# Include <stdio. h> # include <stdarg. h> double sum (INT num, double F1 ,...) {va_list P; double out = F1; va_start (p, F1); While (-- num) {F1 = va_arg (p, double); out + = F1 ;} va_end (p); Return (out) ;}int main (void) {printf ("% G \ n", sum (3, 1.1, 2.2, 3.3 )); /* 6.6 */printf ("% G \ n", sum (2, 1.1, 2.2, 3.3);/* 3.3 */getchar (); Return 0 ;}
4. Sum of integers and floating-point numbers:
In this example, the printf function style is simulated, but only integers and floating-point numbers are supported.
# Include <stdio. h> # include <stdarg. h> double sum (char * STR ,...) {va_list list; double out = 0.0; va_start (list, STR); While (* Str) {If (* STR = '% ') {Switch (* (++ Str) {Case 'D': Out + = va_arg (list, INT); break; Case 'F': Out + = va_arg (list, double); break ;}}str ++;} va_end (list); Return (out) ;}int main (void) {double D = sum ("% d, % F, % d, % F ", 1, 1.1, 2, 2.2); printf (" % G \ n ", d);/* 6.3 */getchar (); return 0 ;}