1、使用以下三个函数可实现不定参数
#include<stdarg.h>
void va_start(va_list ap, last);
type va_arg(va_list, type);
void va_end(va_list ap);
《1》、va_start
该函数用来初始化指针变量ap(va_list实际是void类型),之后处理参数就默认从ap开始处理。last一般为传过来的参数列表的第一个参数。
《2》、va_arg
该函数就是将ap指针按照type类型向后移动,然后返回ap所指的那个参数。
注意:
type类型不能是float,其它不支持暂不知(测试过char ,int, short均可以)
《3》、va_end
和va_start配套使用,做善后。
#include <stdio.h>
#include <stdarg.h>
int sum(unsigned int count, const int , ...);
int main(void)
{
printf("The result is:%d\n", sum(3, 10, 9, 8));
return 0;
}
int sum(unsigned int count, const int first, ...)
{
va_list argp;
int i;
int sum = 0;
int tmp;
va_start(argp, first);
sum += first;
printf("%d\n", first);
for ( i = 1; i < count; i++)
{
/* code */
tmp = va_arg(argp, int);
printf("%d\n", tmp);
sum += tmp;
}
va_end(argp);
return sum;
}
结果:
10
9
8
The result is:27
2、可变参数宏 …
和__VA_ARGS__
C99规范中新增的宏
通过宏的方式可以在
语言中自定义打印的输出函数,不在打印的函数中增加例如行、函数名或者所在的文件名等,该例子采用自定义打印不定参数函数的例子来举例。
#include <stdio.h>
#include <stdarg.h>
#define debug(format, ...) do{\
printf("Info %s,%s,%d, "format"\n",__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__);\
}while(0)
int test(int count, short first, ...)
{
va_list argp;
int sum = 0;
int tmp = 0;
va_start(argp, first);
printf("%d \t", first);
for (int i = 1; i < count; ++i)
{
debug("%d \t", va_arg(argp, int));
//printf("%d \t", va_arg(argp,short));
}
va_end(argp);
return 0;
}
int main()
{
test(10, 5, 6, 8, 9, 10, 56, 89, 52, 21, 110);
// getchar();
return 0;
}
其中自定的打印参数为:
#define debug(format, ...) do{\
printf("Info %s,%s,%d, "format"\n",__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__);\
}while(0)
详解:
debug的第一个参数format为待打印信息的格式,和print函数中的%d、%s等类似。
在print中需要在打印字符串中将格式化的参数用双引号表示这个是输入的格式参数。不是需要打印的字符串。
我们可以使用一个简单的自定义的打印函数来测试一下format参数的含义
#define debug(format, ...) fprintf(stdout, format, __VA_ARGS__)
以上程序运行的结果为:
5 Info a.c,test,44, 6
Info a.c,test,44, 8
Info a.c,test,44, 9
Info a.c,test,44, 10
Info a.c,test,44, 56
Info a.c,test,44, 89
Info a.c,test,44, 52
Info a.c,test,44, 21
Info a.c,test,44, 110