/*
* @Date: 2019-8-27 11:44:24
* @Author: tracycw
* @Description: 可变参数
*/
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdarg.h>
using namespace std;
double average(int num, ...)
{
va_list valist;
double sum = 0.0;
int i;
/* 为 num 个参数初始化 valist */
va_start(valist, num);
/* 访问所有赋给 valist 的参数 */
for (i = 0; i < num; i++)
{
sum += va_arg(valist, int);
}
/* 清理为 valist 保留的内存 */
va_end(valist);
return sum / num;
}
int main()
{
cout << "Average of 2, 3, 4, 5 = " << average(4, 2, 3, 4, 5) << endl;
cout << "Average of 5, 10, 15 = " << average(3, 5, 10, 15) << endl;
system("pause");
return 0;
}
va_start:
_crt_va_start:
/*
* @Date: 2019-8-27 11:44:24
* @Author: tracycw
* @Description: 可变参数(函数参数的传递存储在栈中,从右至左压入栈中,压栈过程为递减)
*/
#include <stdio.h>
void test(unsigned int num, ...)
{
unsigned int i = 0;
unsigned int *addr = #
for (i = 0; i <= num; i++)
{
/* *(addr + i) 从左往右依次取出传递进来的参数,类似于出栈过程 */
printf("i=%d, value=%d\n", i, *(addr + i));
}
}
int main()
{
test(3, 1, 2, 3);
return 0;
}