Passing types to a subroutine

Clay Jackson clayj at microsoft.UUCP
Fri Nov 11 10:35:46 AEST 1988


In article <14461 at mimsy.UUCP> chris at mimsy.UUCP (Chris Torek) writes:
>>need to do is something of the following:
>[edited]
>>	subroutine(...., <float array>, ...);
>>	subroutine(...., <double array>, ...);
>>
>>and have the subroutine do the right thing with a[].
>
>This is easy: you cannot do it at all in C.
>
>The best approximation is something like this:
>
(edited for brevity)
>	float a[100];
>	subroutine(TYPE_FLOAT, a, (double *)NULL);
>	...
>
>	double a[100];
>	subroutine(TYPE_DOUBLE, (float *)NULL, a);

Another approach, which I have seen implemented in a commercial product
(NOT made by Microsoft!) is to define a union, ala:

union foo {
  long long_arg;
  short short_arg;
  double double_arg;
 };

Then, reference it in a struct

 struct myargs {
    union foo my_val;
    int arg_type
 };

Then you can even get fancier, and use defines to set up names, like 
#define LONG 0
#define SHORT 1
.
.
and so on, to figure out what the value of arg_type should be.

I first saw this used in "Unify", a database product made by the Unify Corp.
There is nothing, as far as I know, proprietary about it, and it seems like
a pretty elegant solution for something that would otherwise be pretty hard
to do in C.



More information about the Comp.lang.c mailing list