Variable parameters in C Language
The function of variable parameters in C language is really very large. Since I published an article on how to implement printf, fprintf, and sprintf, many bloggers have asked me about the mechanism, I also explained the related knowledge points. Today, we take this opportunity to give an example to see how to use a variable parameter to accumulate and return data. Please refer to the Code:
# Include
# Include
Int add (int count ,...) {va_list ap; int I, sum; va_start (ap, count);/* Initialize the argument list. */sum = 0; // accumulate all integers in the passed parameter for (I = 0; I <count; I ++) sum + = va_arg (ap, int);/* Get the next argument value. */va_end (ap);/* Clean up. * // return the accumulated value return sum;} int main (void) {printf ("% d \ n", add (3, 5, 5, 6 )); printf ("% d \ n", add (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return 0 ;}
Running result:
We can see that after the input parameters are added, the result returned by printf is the result returned by the function.