#include <stdio.h> #include <stdarg.h> double testArgFunc(int num, ...) { // 创建一个参数列表 va_list valist; double sum = 0.0; // 为num个参数初始化valist va_start(valist, num); // 访问所有赋值给valist的参数 int i = 0; for (i; i < num; i ++) { sum += va_arg(valist, int); } //清理为valist保留的内存; va_end(valist); return sum; } void main(int argn ,char *argv) { printf("test1 sum:%f ", testArgFunc(4, 2,3,6,4)); printf("test2 sum:%f ", testArgFunc(2, 3,9,10)); }
输出结果:
test1 sum:15.000000 test2 sum:12.000000
使用案例2
#include <iostream> #include <stdarg.h> #include <stdio.h> void test(const char *fmt, ...) { char buf[1024]; va_list ap; va_start(ap, fmt); vsprintf(buf, fmt, ap); printf("wyq, %s ", buf); va_end(ap); } int main(int argc, char **argv) { test("nihao"); test("hello world:%s:%02d", "2020", 06); return 0; }