This section contains an implementation of a minimal version of printf, to show how to write a function that processes a variable-length argument list in a portable way. Since we are mainly interested in the argument processing, minprintf will process the format string and arguments but will call the real printf to do the format conversions. The proper declaration for printf is int printf(char *fmt, ...) where the declaration ... means that the number and types of these arguments may vary. The declaration ... can only appear at the end of an argument list. Our minprintf is declared as void minprintf(char *fmt, ...) since we will not return the character count that printf does. The tricky bit is how minprintf walks along the argument list when the list doesn't even have a name. The standard header
#include
/* minprintf: minimal printf with variable argument list */ void minprintf(char *fmt, ...) {
va_list ap; /* points to each unnamed arg in turn */
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt); /* make ap point to 1st unnamed arg */
for (p = fmt; *p; p++)
{
if (*p != '%')
{ putchar(*p);
continue;
} switch (*++p) { case 'd':
ival = va_arg(ap, int);
printf("%d", ival);
break; case 'f':
dval = va_arg(ap, double);
printf("%f", dval);
break;
case 's':
for (sval = va_arg(ap, char *); *sval; sval++)
putchar(*sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap); /* clean up when done */
}
No comments:
Post a Comment