A variable parameter function represents: type fun (int num, ...)
Wherein the type represents the type of function return value, NUM represents the number of parameters, and "..." indicates all parameters.
Example: char fun (int num, ...);
Two, va_list, va_start (), va_arg (), va_end () function and the original meaning of representation.
1, va_list: represents the parameter list.
2, va_start (): a list of initialization parameters.
3, va_arg (): Get a different type parameters.
4, va_end (): Empty the list of parameters.
5、typedef char * va_list;
#define _INTSIZEOF(n) ((sizeof(n)+sizeof(int)-1)&~(sizeof(int) - 1) )
#define va_start(ap,v) ( ap = (va_list)&v + _INTSIZEOF(v) )
#define va_arg(ap,t) ( *(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)) )
#define va_end(ap) ( ap = (va_list)0 )
6, (a + b-1) & ~ (b-1): When a and b are both n-th power of 2, can be obtained the smallest multiple of the maximum of a and b.
Therefore, (sizeof (n) + sizeof ( int) -1) & ~ (sizeof (int) - 1) may be used for byte alignment.
#include <stdio.h> #include <stdarg.h> int FUNC ( int NUM, ...) // NUM representative of the number of parameters { char ** ARR; int Inter [ 2 ]; Double Dou [ . 3 ]; int I; the va_list list; // parameter list the va_start (list, NUM); // initialization parameter list for (I = 0 ; I < 2 ; I ++ ) { Inter [I] = the va_arg (list, int ); // Get int type parameter printf ( " inter[%d]=%d\n",i,inter[i]); } for(i=0;i<3;i++){ dou[i]=va_arg(list,double); // 获取double类型参数 [Warning] 'float' is promoted to 'double' when passed through '...' printf("dou[%d]=%lf\n",i,dou[i]); } for(i=0;i<5;i++){ arr[i]=va_arg(list,char*); // 获取int类型参数 printf("arr[%d]=%s\n",i,arr[i]); } return 0; } int main(){ func(10,1,2,1.0,2.0,3.0,"aaa","bbb","ccc","ddd","eee"); }