Article From:
//Here is a simple implementation of printf (non-original)
//Use in the order of va_list, va_start, va_copy, va_arg, va_end
//Note: 1.void va_start( va_list ap, parmN );The second parameter is the last fixed parameter in the list of parameters you define. 2.T va_arg( va_list ap, T );Type T will be doped with type promotion of C language, such as automatic type conversion of char-> int float-> double.
#include <stdio.h> #include <stdarg.h>   void simple_printf(const char* fmt, ...) { va_list args; va_start(args, fmt);   while (*fmt != '\0') { if (*fmt == 'd') { int i = va_arg(args, int); printf("%d\n", i); } else if (*fmt == 'c') { // Note the automatic conversion to integer typeint c = va_arg(args, int); printf("%c\n", c); } else if (*fmt == 'f') { double d = va_arg(args, double); printf("%f\n", d); } ++fmt; }   va_end(args); }   int main(void) { simple_printf("dcff", 3, 'a', 1.999, 42.5); }

Leave a Reply

Your email address will not be published. Required fields are marked *