a simple program demostrate c variable-length argument lists, and how to refer variable-length argument in c macro.
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
//fmt: %d%s
void min_printf(char *fmt, ...)
{
va_list ap;
char *p;
int val;
char *s;
va_start(ap, fmt);
//vprintf(fmt, ap);
//va_end(ap);
//return;
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
switch(*++p) {
case 'd':
val = va_arg(ap, int);
printf("%d", val);
break;
case 's':
s = va_arg(ap, char *);
printf("%s", s);
break;
default:
putchar(*p);
}
}
va_end(ap);
}
// both work
//#define printf(fmt, args...) printf("func: %s, line: %d, "fmt, __FUNCTION__, __LINE__, ##args)
//#define printf(fmt, args...) printf(fmt"func: %s, line: %d, ", ##args, __FUNCTION__, __LINE__)
#define printf(fmt, args...) printf("%s(), #%d, "fmt, __FUNCTION__, __LINE__, ##args)
//#define printf(...) printf("%s(), #%d, "fmt, __FUNCTION__, __LINE__, __VA_ARGS__)
//#define printf(...) printf(__VA_ARGS__)
int main()
{
printf("int %d, str: %s\n", 123, "this is us");
printf("end\n");
min_printf("int %d, str: %s\n", 123, "this is us");
min_printf("end\n");
return 0;
}