I've been reviewing stuff from multiple sources including my old favorite K&R second ed.
I've been looking at variadic functions, and almost all the tutorials I've seen use and int
before the ellipses to determine the total number variable arguments passed.
But K&R example in the book does not use an int
, they uses a char *
I searched stackoverflow and found stuff like:
Any variadic function must have a way for the caller to specify the number and types of arguments. The *printf functions, for example, do so via the (non-variadic) format string. link
and
No -- C doesn't define end as having any special meaning with varargs. When you write a function that takes a variable argument list, it's up to you to decide how to tell it how long of a list has been passed. link
K&R minprintf is meant to show how to use variadic function.
---- 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
K&R only show the function, I added the main at the bottom, to see if it would work. I compiled it with gcc -Wall test.c
. It compiled with no warnings, and worked as expected. The code is:
#include <stdarg.h>
#include <stdio.h>
/* 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 */
}
// I added this main below to test K&R minprintf function. It compiled no errors and gave right answer.
int main()
{
int i = 25;
int j = 21;
char str[] = "This is a test";
minprintf("%d, %d, %s\n", i, j, str);
}
How does minprintf
know when to end? Is there a NULL
in there? K&R do not explain it. From the stuff I read on-line, and some of the quotes above, a variadic functions does not know where to end, unless you tell it, such as with an int before the ellipses.