Re: Elegant way to eliminate large conditional?
Re: Elegant way to eliminate large conditional?
- Subject: Re: Elegant way to eliminate large conditional?
- From: Jeff Szuhay <email@hidden>
- Date: Mon, 6 Jan 2003 15:41:21 -0500
I'm developing a program that includes a unit converter which, among
other things, can convert from any one of five temperature scales to
any of the other five temperature scales. The code is hard to
maintain, unfortunately, as I use a rather long conditional (with
multiple sub-conditionals) to determine the "to" and "from" scales.
Is there some (elegant) way to use a matrix-like setup (a
two-dimensional selector or even an array?) that, given two
arguments (a range of five numbers, for each of the temperature
scales) will execute a different one of 25 equations or selectors?
These are called "jump tables" in Fortran and C, and often used in
instruction parsers for high
performance computing (but not necessarily pretty). This is just basic C code.
So, you would have a two dimensional array, with one index for the
"from" scale, and the other for
the "to" scale. The contents of each element of the array would be a
C function pointer to one of
a set of functions that takes an input value and returns the
converted value (the signatures of each
of the functions should all be the same).
You first have to define (not just declare) each of the converters
typedef <<your_intrinsic_temp_type>> Temp_Type;
Temp_Type convert1to2( Temp_Type inTemp)
{
Temp_Type outTemp;
// convert code
...
return outTemp;
}
Temp_Type convert1to2( Temp_Type inTemp )
{
Temp_Type outTemp;
// convert code
...
return outTemp;
}
...
Then you'd initialize the elements of the array to the function entry
points (addresses)
(void *) jump[4][4] = {0};
jump[0][0] = &(convert1to1)();
jump[0][1] = &(convert1to2)();
...
then you'd just call the function
double convert( int from, int to, double tempIn)
{
(void *) *fp = jump[from][to];
return ((*fp)( tempIn ));
}
but now, I have to get out my "C syntax scrabble board" as I'm not
sure the sample code is
exactly correct.
I can find some working examples if you decide to go this route, just
let me know.
Jeff Sz.
--
Jeff Szuhay <
mailto:email@hidden>
Lead Macintosh Engineer voice: 412-271-5040 x 227
Psychology Software Tools <
http://www.pstnet.com/>
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.