Re: function definition
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Wed, 01 Oct 2008 00:02:06 -0700
Tinkertim <tinkertim@xxxxxxxxx> writes:
On Oct 1, 1:01 pm, Keith Thompson <ks...@xxxxxxx> wrote:
The point is that a printf-style format string isn't the only way to
determine the number and type of arguments that are supposed to be
passed (though I think it's the only method used by any of the
functions in the standard library).
Your correct on the latter, I took a stroll through a few libc
implementations and only saw it in the printf core or things that use
it.
For example, I've seen variadic
functions that take a series of char* arguments, with the end of the
list marked by a (char*)NULL argument.
In that example, the function assumes all arguments to be char * type,
yes? You know your done when you hit a null argument. I'm not sure how
you could mix types without passing some kind of definition of the
incoming format.
I wasn't saying that a format was needed in all cases, just in cases
where arguments are of mixed types .. or is that what you were saying
that you've seen done? Sorry if I'm a little dense today :)
A format *string* is just one of many possible ways to specify the
arguments. Here's a rather contrived example:
#include <stdarg.h>
#include <stdio.h>
enum arg_type { INT, DOUBLE, STRING, END };
void func(enum arg_type first, ...)
{
va_list ap;
enum arg_type next_arg_type = first;
va_start(ap, first);
do {
switch(next_arg_type) {
case INT: {
int i = va_arg(ap, int);
printf("int: %d\n", i);
break;
}
case DOUBLE: {
double d = va_arg(ap, double);
printf("double: %g\n", d);
break;
}
case STRING: {
char *s = va_arg(ap, char*);
printf("string: \"%s\"\n", s);
break;
}
case END: {
/* nothing */
}
}
next_arg_type = va_arg(ap, enum arg_type);
} while (next_arg_type != END);
va_end(ap);
}
int main(void)
{
func(INT, 42, STRING, "hello", DOUBLE, 1.23, END);
return 0;
}
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.
- Follow-Ups:
- Re: function definition
- From: Tinkertim
- Re: function definition
- References:
- Re: function definition
- From: Tinkertim
- Re: function definition
- From: Keith Thompson
- Re: function definition
- From: Tinkertim
- Re: function definition
- Prev by Date: Re: function definition
- Next by Date: Re: Looping Choice
- Previous by thread: Re: function definition
- Next by thread: Re: function definition
- Index(es):
Relevant Pages
|