要实现printf函数需要考虑如下三点:
1.如何告诉printf传入参数的个数:参数个数不确定。
2.printf如何访问到这些参数。
3.函数调用完成后,系统如何释放在堆栈的参数。
printf函数的定义:(原型)
int _cdecl printf(const char* format,...);
注:_cdecl是C/C++缺省调用方式。
_cdecl调用约定:1.参数从右自左依次入栈。 2.调用者负责清理堆栈。 3.参数的数据类型不会导致编译阶段的错误。
实现如下:
#include <stdio.h>
#include <stdarg.h>
void myprintf(const char *format, ...)
{
va_list ap;
char ch;
va_start(ap, format);
while(ch = *format++)
{
switch(c)
{
case 'c':
{
char ch1 = va_arg(ap, char);
putchar(ch1);
break;
}
case 's':
{
char *p = va_arg(ap, char *);
fputs(p,stdout);
break;
}
default:
putchar(ch);
}//switch结束
}//while 结束
va_end(ap);
}//myprintf结束
void main()
{
myprintf("c\ts\n",’A’,"hello");
}
typedef char * va_list;
#define _INTSIZEOF(n)
( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )
#define va_start(va_list ap, format)
( ap = (va_list)& format+ _INTSIZEOF(format) )
#define va_arg(va_list ap,type)
( *(type*)((ap += _INTSIZEOF(type)) -_INTSIZEOF(type)) )
#define va_end(va_list ap)
( ap = (va_list)0 )