C++可变参数的另一种实现
作者:网络转载 发布时间:[ 2013/6/9 13:33:07 ] 推荐标签:
大家熟知的C库函数printf函数是一个可变参数函数,它是怎么实现的呢?不过他实现是有条件的,必须函数参数的入栈顺序为从右向左的顺序,也即函数的形参,在函数调用之前,必须是右边的参数先入栈,并且参数都必须通过栈传递,以1个例子说明,如函数func(arg1, arg2,arg3),那么函数的堆栈应是:
ebp是帧指针寄存器,一般用来存取堆栈,有了堆栈结构,下面我们看看C可变参数的具体实现原理:
#include <stdio.h>
enum {
ptChar,
ptInt,
ptFloat,
ptDouble,
};
void printSum(unsigned long paramFormat, ...)
{
/*高16位为可变参数类型,低16位为可变参数个数*/
int paramType = (paramFormat >> 16);
int paramNum = paramFormat & 0xffff;
/*¶mFormat = ebp + 8,第一个参数的地址*/
unsigned long *pArg = ¶mFormat;
/*ebp + 0x0c, 第二个参数地址*/
pArg++;
switch(paramType)
{
case ptChar:
{
int sum = 0;
for (int i = 0; i < paramNum; i++)
{
char *pValue = (char *)pArg;
sum += *pValue;
pArg++;
}
printf("%d
", sum);
}
break;
case ptInt:
{
int sum = 0;
for (int i = 0; i < paramNum; i++)
{
int *pValue = (int *)pArg;
sum += *pValue;
pArg++;
}
printf("%d
", sum);
}
break;
case ptFloat:
{
float sum = 0;
/**/
pArg++;
/*浮点参数,堆栈占8个字节,所以指针偏移为8*/
for (int i = 0; i < paramNum; i++)
{
float *pValue = (float *)pArg;
sum += *pValue;
pArg++;
pArg++;
}
printf("%f
", sum);
}
break;
case ptDouble:
{
double sum = 0;
/*双精度浮点参数,堆栈占8个字节,所以指针偏移为8*/
for (int i = 0; i < paramNum; i++)
{
double *pValue = (double *)pArg;
sum += *pValue;
pArg++;
pArg++;
}
printf("%f
", sum);
}
break;
default:
printf("unknowned type!
");
break;
}
}
void main()
{
unsigned long paramFormat = 3;
char a = 1, b = 2, c = 3;
printSum(paramFormat, a, b, c);
paramFormat = ptInt << 16;
paramFormat += 3;
int ia = 1, ib = 2, ic = 3;
printSum(paramFormat, ia, ib, ic);
paramFormat = ptFloat << 16;
paramFormat += 3;
float fa = 1, fb = 2, fc = 3;
printSum(paramFormat, fa, fb, fc);
paramFormat = ptDouble << 16;
paramFormat += 3;
double da = 1, db = 2, dc = 3;
printSum(paramFormat, da, db, dc);
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11