Passing types to a subroutine

Wayne Mesard mesard at bbn.com
Fri Nov 11 01:17:54 AEST 1988


>From article <14461 at mimsy.UUCP>, by chris at mimsy.UUCP (Chris Torek):
> In article <14457 at mimsy.UUCP> sjr at mimsy.UUCP (Stephen J. Roznowski) writes:
>>I'm in the process of developing a piece of code that needs
>>to be portable across several different machines.  What I
>>need to do is something of the following:
> [edited]
>>	subroutine(...., <float array>, ...);
>>	subroutine(...., <double array>, ...);
>
> The best approximation is something like this:
> 
> 	float a[100];
> 	subroutine(TYPE_FLOAT, a, (double *)NULL);
> 	...
> 
> 	double a[100];
> 	subroutine(TYPE_DOUBLE, (float *)NULL, a);
> 	...
> 
> 	subroutine(t, iffloat, ifdouble)
> 		enum whichtype t;
> 		float *iffloat;
> 		double *ifdouble;
[Rest deleted.]

Or, how 'bout using a good old union to get rid of the extra param:

   union ptr {
       float *f;
       double *d;
   };

   enum whichtype {TYPE_FLOAT, TYPE_DOUBLE};

   main()
   {
       void sub();
       float f[10];
       double d[10];

       f[1] = 1.234;
       d[1] = -5.432;
       sub(0, f);
       sub(1, d);
       printf("Incidently, the sizeof the union is %d\n", sizeof(union ptr));
   }


   void sub(t, p)
   enum whichtype t;
   union ptr p;
   {
       switch(t) {
	 case TYPE_DOUBLE:
	   printf("Itsa double, cell 1 is %g\n", p.d[1]);
	   break;
	 case TYPE_FLOAT:	
	   printf("Itsa float, cell 1 is %g\n", p.f[1]);
	   break;
       }
   }

-- 
void *Wayne_Mesard();         MESARD at BBN.COM         BBN, Cambridge, MA



More information about the Comp.lang.c mailing list