Results 1 to 4 of 4
Hi,
I'm looking for an algorithm to efficiently determine the ordinal position of a non-linear enum. Suppose I have:
Code:
typedef enum NewTypeT
{
ABC = 5,
DEF,
GHI,
JKL ...
- 10-02-2009 #1Just Joined!
- Join Date
- Jun 2009
- Posts
- 20
ANSI C: ordinal position of enum
Hi,
I'm looking for an algorithm to efficiently determine the ordinal position of a non-linear enum. Suppose I have:
Then I'm after a function (or macro?) to evaluate the position of an enum's declaration. Something like:Code:typedef enum NewTypeT { ABC = 5, DEF, GHI, JKL = 73, MNO, PQR } NewType;
Any ideas?Code:int ordinal(NewType n) { /* work out ordinal position of n */ } void foo(void) { int x = ordinal(MNO); /* x should be 5 because "MNO" is the fifth element */ }
- 10-02-2009 #2Linux Guru
- Join Date
- Apr 2009
- Location
- I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
- Posts
- 8,974
Sorry, but there is no way to do this without you providing some sort of means to associate the enum (which is basically a global variable) and its position in the set, such as using an array to hold the values. Example:
NewType NTordinal[] = { ABC, DEF, GHI, JKL, MNO, PQR };
Now, you can determine the position of each in the array and since each entry is kept in sync with the enum list itself, there you are. You just have to remember to update the array when you add/remove/change the enums. Your ordinal function could also use a switch statement to do the same and return the values. IE,
Code:switch (NewType t) { case ABC: return 0; . . . case PQR: return 5; default: return -1; }Sometimes, real fast is almost as good as real time.
Just remember, Semper Gumbi - always be flexible!
- 10-03-2009 #3
Rather than do this by algorithm, you may find it easier to just add a simple array to assist with this - you give up some memory for convenience, e.g.
Don't forget to put a comment into your enum so that if someone changes it they update the array. Then when you want an ordinal, just search the array, the index where you find it is the ordinal you want. If you do this, you might want to include an 'end of list' marker, to make the searching easier to detect the end.Code:typedef enum NewTypeT { ABC = 5, DEF, GHI, JKL = 73, MNO, PQR } NewType; const NewType NewTypeOrdinals[] = {ABC, DEF, GHI, JKL, MNO, PQR};
You could even do this kind of thing with an stl container, such as a map, if you want to do this without even having to write the search code.Linux user #126863 - see http://linuxcounter.net/
- 10-05-2009 #4Just Joined!
- Join Date
- Jun 2009
- Posts
- 20
Thanks for your answers. This is a great head start to solving my problem.


Reply With Quote