Archived

This topic is now archived and is closed to further replies.

number of items inside enum?

This topic is 5004 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a command to get the number of items inside an enum? basically if i had: enum LALA { hello, how, are, you, today, }; i want to know that there are 5 items in there... i tried sizeof(LALA), but that returned 4 (the size of an int basically). But i was wondering if there is some way of determining how many items there are in there? basically i want to set up an array of ints, one int for each item... and instead of just hard-coding it as 5, i want to be able to set the array size depending on the number of items in there so that if i change it, the size of the array will also change. Thanks.

Share this post


Link to post
Share on other sites
The value of items in an enum is zero based. So if you declare your enum like:

enum LALA {
hello,
how,
are,
you,
today,
number_of_LALAs
};

number_of_LALAs should be the number of LALAs as long as you have it as your last value and you don''t mess with the numbering.

Share this post


Link to post
Share on other sites
If you don''t care about the actual values, the easiest way is to do this:

enum LALA
{
hello, // = 0 by default
how,
are,
you,
today,
LALA_COUNT
};


Just make sure that whenever you add new items, you add them before LALA_COUNT. Then, you can use LALA_COUNT for the number of values, but this only works if you don''t define the values yourself and you let them start at 0 and increment by 1 each time. In this case, LALA_COUNT would be a constant defined to be 5, and there are indeed 5 values of LALA variables (not including LALA_COUNT itself, of course).

Share this post


Link to post
Share on other sites
Just keep in mind that you can reset the count in your enum whenever you feel like:
enum Day {
Sunday = 0,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday = 0
};
In this instance, you can detect a weekday by a non-zero value, but Saturday is no reliable indicator of number of elements, and adding a NUM_OF_DAYS value after Saturday wouldn''t help as its integer value would be 1.

Enums are only zero-based by default. If you have control of the enum from declaration then it''s no problem, but if you''re relying on external enumerations, there''s no practical way to programmatically determine size.

Share this post


Link to post
Share on other sites
I realise that.. i''m not gonna be changing the counting of the enum.. i''m making a 3d pool type game, and i just have an enum containing the colors of the pool balls... so as long as each of the entries are unique i don''t care what they are, so no need to screw around with it.

Share this post


Link to post
Share on other sites