Learning Exchange can be added
Micro-channel reader exchanges ① group (add micro letter: coderAllen)
programmer technology exchange ① QQ group: 736 386 324
---
Provided: ANSI C in order to improve portability, provides ease of use a set of macros vararg through the header file stdarg.h
We consider writing a copycat version of the printf (), named tiny_printf ()
The first parameter tiny_printf () to specify the type of follow-up of each parameter, the second parameter specifies the start value required output
tiny_printf ( "sdd", " result .. ", 3, 5) ;
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
void tiny_printf(char *format, ...) //原型声明的参数中出现…, 对于这部分的参数是不会做类型检查的
{
int i;
va_list ap; //typedef char * va_list;
va_start(ap, format); //使指针 ap 指向参数 format 的下一个位置,得到了第一个参数
for (i = 0; format[i] != '\0'; i++) {
switch (format[i]) {
case 's':
printf("%s ", va_arg(ap, char*));
break;
case 'd':
printf("%d ", va_arg(ap, int));
break;
default:
assert(0);
}
}
va_end(ap); //标准里指出了对于具有 va_start()的函数需要写 va_end()
putchar('\n');
}
int main(void)
{
tiny_printf("sdd", "result..", 3, 5);
return 0;
}
Watch for more exciting articles scan code [Allen something to say], to focus on programming, workplace, English (foreign)