C Language Learning 020: Variable Parameter functions, language learning 020
As the name suggests, a variable parameter function is a variable parameter function, that is, the number of parameters of a function is uncertain. For example, if the getnumbertotal () method is used, we can pass a parameter, you can also pass 5 or 6 parameters.
1 # include <stdio. h> 2 # include <stdarg. h> // header file 3 4 int getnumbertotal (int args,...) required for variable parameters ,...) {// variable parameters should be placed behind the regular parameters (args ;... it indicates that there are many parameters 5 va_list l; // other parameters 6 va_start (l, args) used to save the passed to function; // It indicates the start of a variable parameter, 7 int I; 8 int total = 0; 9 // read variable parameters one by one 10 for (I = 0; I <args; I ++) {11 total + = va_arg (l, int); 12} 13 va_end (l); // destroy va_list14 return total; 15} 16 17 int main () {18 int result = getnumbertotal (,); 19 printf ("total: % I \ n", result); 20 result = getnumbertotal (, 9 ); 21 printf ("total: % I \ n", result); 22 result = getnumbertotal (5, 11, 9, 5, 13, 7); 23 printf ("total: % I \ n ", result); 24 return 0; 25}
When using variable parameters, you must note that a common parameter must be included.
We can pass a NULL value to the va_start () method, but we need to know the number of variable parameters through the first parameter.
Va_arg must be of the corresponding type when obtaining variable parameters; otherwise, an unpredictable error may occur.