R
Richard Bos
Grumble said:I have the following structure:
struct foo {
char *format; /* format string to be used with printf() */
int nparm; /* number of %d specifiers in the format string */
/* 0 <= nparm <= 4 */
};
e.g.
struct foo bar = { "foo %d %d bar %d\n", 3 };
I can write:
printf(bar.format, rand(), rand(), rand());
Yes. Note that you don't know in which order the rand()s are called.
With rand(), this is obviously not of great importance, but if you
substitute a function which pops a value from a stack instead, you might
be in for a surprise...
Assume I have a properly initialized array of struct foo:
struct foo array[100]; ... /* initialize array */
and I want to print every struct foo. Do I have to make a special case
for every possible value of nparm? As in:
for (i=0; i < 100; ++i)
{
switch(array.parm)
{
case 0:
printf(array.format); break;
case 1:
printf(array.format, rand()); break;
...
case 4:
printf(array.format, rand(), rand(), rand(), rand()); break;
}
}
You do if you really need to use printf(). If you know in advance that
the maximum number of parameters is limited, this isn't such a bad
approach.
Isn't there a better way? If I think in terms of a stack (which I know
is a sin in c.l.c.)
You know nothing of the sort. Why would using stacks be a sin? What you
can't do in ISO C is use any kind of system, hardware or program stack,
but there's nothing to prevent you from creating your own stack ADT.
I should be able to push however many parameters I
have onto the stack, push either the number of arguments or NULL (I'm
not sure how printf works) and then jump to the the printf code.
Ah, well, _that_ is impossible. printf() doesn't know how to use your
stack, and you can't interfere with its stack. I wouldn't even try if
you could, either; much too risky.
I've never used variadic functions.
(Yes, you have; printf() is one.)
Could they prove useful in this case?
Not that I can see. <stdarg.h> is for writing functions that get
variable numbers of arguments passed to them, not for passing variable
numbers of arguments to other functions. It would have been useful had
that been possible, but alas, it isn't.
Richard