您的位置:首页 > 其它

可变参数列表的宏和<stdarg.h>实现函数的可变参数列表

2015-04-07 13:39 162 查看
标准头文件<stdio.h>中的printf()函数很诡异,它有一个可变的参数列表。

下面是自己实现的printf()函数。

#include <stdio.h>      /* printf, vprintf*/
#include <stdarg.h>     /* va_list, va_start, va_copy, va_arg, va_end */
#include <stdint.h>

void myprintf(const char * format, ...) {
va_list vl;

va_start(vl, format);
vprintf(format, vl);
va_end(vl);
}

int main () {
uint8_t x = 1, y = 2;
float d = 3.1415926f;

myprintf("Hello world !\n");
myprintf("these numbers are: %hhd %hhd %f\n", x, y, d);
return 0;
}
 


...与__VA_AGRS__

#include <stdio.h>
#include <stdint.h>
/* 可变宏:...和__VA_ARGS__ */
#define myprintf(...); { \
printf("Do something before it.\n"); \
printf(__VA_ARGS__); \
printf("Do something after it.\n"); \
}

void main() {
uint8_t x = 1, y = 2, z = 3;
myprintf("x=%hhu,y=%hhu,z=%hhu\n", x, y, z);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: