Michael wrote:
Hi all,
I've got a question according the design
of a parameterlist in C. I am going to have
a function taking two parameters.
One is supposed to be used as a flag, which
determines the type of data is needed, which
is passed to the function by the second parameter.
The type of this parameters differs depending on
the flag. E.g.
void doSomething ( int flag, <seeBelow> value)
{
...
switch flag
{
case 1: // I need value to be a double
...
case 2: // Value shoud be an int
...
}
...
}
Since the number of different types is finite,
I wonder what is the best bet to pass the 2nd Parameter
a) Build a struct, containing all possibilities
of which only the needed are set
b) Use a void pointer
c) Something else
infinity of possiblities is a problem with all:
a) defining a struct(union) can be done but you have to
define all possiblities.
b) You can use void pointer but again your possibilities
are limited.
Of these two I would favor the second (void *). However
to give more flexible why not use the variable argument
macros.
/* The program below illustrates passing a variable
* arguments using the following macros:
* va_start va_arg va_end
* va_list
*/
#include <stdio.h>
#include <stdarg.h>
typedef enum {CHARPOINTER,DOUBLE,INTEGER,INTSUM} type;
void functest( type flag, ... );
int main(void)
{
functest(CHARPOINTER,"This is a test");
functest(DOUBLE, 12.20);
functest(INTEGER, 23);
functest(INTSUM,23,23);
functest(44,29);
return 0;
}
/* Testing variable arguments */
void functest( type flag, ... )
{
va_list marker;
va_start( marker, flag ); /* Initialize variable arguments. */
switch(flag)
{
case CHARPOINTER: printf("The argument is a char *\n"
"pointing to string \"%s\"\n\n",
va_arg(marker,char *));
break;
case DOUBLE: printf("The argument is a double\n"
"of value %f\n\n",
va_arg(marker,double));
break;
case INTEGER: printf("The argument is a type int\n"
"of value %d\n\n",
va_arg(marker,int));
break;
case INTSUM: {
int i1,i2;
i1 = va_arg(marker,int);
i2 = va_arg(marker,int);
printf("The arguments call for a"
"sumation.\n"
"%d + %d = %d\n\n",i1,i2,i1+i2);
}
break;
default: puts("The agrument is incorrectly specified");
}
va_end( marker ); /* Reset variable arguments. */
return;
}
--
Al Bowers
Tampa, Fl USA
mailto:
xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/