As the name implies, a variable parameter function is a variable number of parameters of the function, that is, the number of parameters of the function is indeterminate, such as the method Getnumbertotal () We can pass a parameter, can also pass 5, 6 parameters
1#include <stdio.h>2#include <stdarg.h>//the header file required to implement the mutable parameter3 4 intGetnumbertotal (intArgs,...) {//the variable parameter should be placed behind the normal parameter (args); Indicates that there are a number of parameters5Va_list l;//other arguments to save to the function6Va_start (L,args);//represents the start of a mutable parameter, which is all arguments after the args parameter7 inti;8 intTotal=0;9 //read variable parameters individuallyTen for(i=0; i<args;i++){ OneTotal+=va_arg (L,int); A } -Va_end (l);//destroying Va_list - returnTotal ; the } - - intMain () { - intResult=getnumbertotal (3, One, the,9); +printf"total:%i\n", result); -Result=getnumbertotal (2, One,9); +printf"total:%i\n", result); AResult=getnumbertotal (5, One,9,5, -,7); atprintf"total:%i\n", result); - return 0; -}
The use of variable parameters must be noted: must contain a common parameter
We can pass a null to the Va_start () method, but we need to know the number of mutable arguments by the first parameter
Va_arg must be a corresponding type when getting variable parameters, otherwise unpredictable errors will occur
C Language Learning 020: variable parameter functions