可变参数最典型的应用就是打印函数的格式化输出,下面就以一个简单的程序讲解
printf函数的实现实际上是依赖于字符的打印,所有打印的实现都离不开字符的打印,下面就以字符的打印实现几个格式化输出的函数,其中主要用到的可变参数。
字符函数的打印就使用:
printf("%c",char);
下面就使用字符的打印实现格式化输出函数
#include <stdio.h>
typedef char * va_list1;
//将char*别名为va_list1,因为会和变量va_list冲突所以改名字为va_list1
#define _INTSIZEOF(n) ((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))
#define va_start(ap,v) (ap = (va_list1)&v + _INTSIZEOF(v))
#define va_arg(ap,t) (*(t*)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)))
#define va_end(ap) (ap = (va_list1)0)
int ZT_PutChar(const char ch)
{
printf("%c",ch);
return ch;
}
void ZT_Printstr(const char *ptr) //输出字符串
{
while(*ptr)
{
ZT_PutChar(*ptr);
ptr++;
}
}
void ZT_PrintInt(const int dec) //输出整型数
{
if(dec == 0)
{
return;
}
ZT_PrintInt(dec / 10);
ZT_PutChar((char)(dec % 10 + '0'));
}
void ZT_PrintFloat(const float flt) //输出浮点数,小数点第5位四舍五入
{
int tmpint = (int)flt;
int tmpflt = (int)(100000 * (flt - tmpint));
if(tmpflt % 10 >= 5)
{
tmpflt = tmpflt / 10 + 1;
}
else
{
tmpflt = tmpflt / 10;
}
ZT_PrintInt(tmpint);
ZT_PutChar('.');
ZT_PrintInt(tmpflt);
}
/*
%i---输出一个整型数;
%d---输出一个整型数;
%f---输出一个浮点数;
%c---输出一个字符;
%s---输出字符串
*/
void zt_printf(const char *format,...)
{
va_list1 ap;
va_start(ap,format); //将ap指向第一个实际参数的地址
while(*format)
{
if(*format != '%')
{
ZT_PutChar(*format);
format++;
}
else
{
format++;
switch(*format)
{
case 'c':
{
char valch = va_arg(ap,int); //记录当前实践参数所在地址
ZT_PutChar(valch);
format++;
break;
}
case 'd':
case 'i':
{
int valint = va_arg(ap,int);
ZT_PrintInt(valint);
format++;
break;
}
case 's':
{
char *valstr = va_arg(ap,char *);
ZT_Printstr(valstr);
format++;
break;
}
case 'f':
{
float valflt = va_arg(ap,double);
ZT_PrintFloat(valflt);
format++;
break;
}
default:
{
ZT_PutChar(*format);
format++;
}
}
}
}
va_end(ap);
}
int main()
{
int a = 5,b = 6;
char c = 'c';
float d = 1.256;
char *buf = "zhang tao hello world\n";
printf(" %i\n %d\n %c\n %f\n %s\n",a,b,c,d,buf);
return 0;
}
函数运行结果为:
上一篇博客:讲述了可变参数的使用方法及注意事项
https://blog.youkuaiyun.com/qq_37600027/article/details/86105962