当前位置:文档之家› Printf函数的实现

Printf函数的实现


的示例( ● printf的示例(四) 的示例
自己写一个printf: : 自己写一个
case 's': { char *p = va_arg(ap, char *); fputs(p,stdout); break; } default: putchar(ch); }//switch结束 结束 }//while 结束 void main() va_end(ap); { }//myprintf结束 结束 myprintf("c\ts\n",'A',"hello"); }
( 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 )
以下为VC++中stdarg.h里x86平台的宏定义 ● 以下为 中 里 平台的宏定义
typedef char * va_list; #define _INTSIZEOF(n) ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) ) #define va_start(va_list ap, format)
● 栈示意图
高地址
… … … 第n个参数 个参数 第n-1个参数 个参数
函数返回地址
可变参数列表 第一个可变参 最后一个固定参 va_arg后ap指向 后 指向 va_start后ap指向 后 指向
低地址

format
的示例( ● printf的示例(三) 的示例
自己写一个printf: : 自己写一个
printf的定义
● printf的声明 的声明 int _cdecl printf(const char* format, …); _cdecl是C和C++程序的缺省调用方式
printf的实现
●_CDEDL调用约定 调用约定
1.参数从右到左依次入栈 参数从右到左依次入栈 2.调用者负责清理堆栈 调用者负责清理堆栈 3.参数的数量类型不会导致编译阶段的错误 参=3; printf("%d",a,b); ( " ); 2. double a=2.345; printf("%d",a); 3. printf("%d"); 4. printf("asd",a);
printf实现原理
★要解决的问题 1.怎么告诉 怎么告诉printf我们会传入几个参 怎么告诉 我们会传入几个参 数 2.printf怎么去访问这些参数 怎么去访问这些参数 3.函数调用完成后,系统怎么把参数 函数调用完成后, 函数调用完成后 从传递用的堆栈中释放
的示例( ● printf的示例(一) 的示例 int __cdecl printf ( const char *format, ... ) { va_list ap; int buffing; int retval; va_start(ap, format); _ASSERTE(format != NULL); _lock_str2(1, stdout); buffing =_stbuf(stdout); retval = _output(stdout,format,ap); _ftbuf(buffing, stdout); _unlock_str2(1, stdout); return(retval); }
C语言可变参函数 语言可变参函数
printf
0724 白雪
printf语法回顾
● 第一段接触的C语言代码 #include<stdio.h> void main() { printf("This is a C program.\n "); }
例1. #define PRICE 30 #include <stdio.h> void main() { int num,total; num=10; total=num*PRICE; printf("total=%d\n",total); }
的示例( ● printf的示例(二) 的示例 函数实现流程: 函数实现流程: va_start(ap, format); retval = _output(stdout,format,ap); 01 while(format[n]){ 02 if (format[n] == "%"){ 03 n++; 04 switch(format[n]){ 05 case 'c': 06 ....... 为例: 以case 'c'为例: 为例 07 case 'd': 08 ....... case 'c': 09 ....... putchar(va_arg(ap, unsigned char)); 10 }//switch cnt_printed_chars++; 11 }//if break; 12}//while 13 va_end(ap);
printf 小结
可变参函数实现总结: ● 可变参函数实现总结: 1.va_系列宏 系列宏 2.堆栈 堆栈 3.所有类型固定的参数都必须出现在参 所有类型固定的参数都必须出现在参 数列表的开始
Thank You! !
0724
白雪

例2. printf("%d,%d\n",sizeof(short),sizeof(int)); 例3. float a,b,c; a=3.141592612; b=2.76543; c=3.456732; printf("%f,%f,%f\n",a,b,c);
例4. char c1,c2,c3,c4; c1='a'; c2='b'; c3='c'; c4='d'; printf("%c,%c,%c,%c\n",c1,c2,c3,c4); 注意: 注意:
#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; }
相关主题