Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of elements in an enum

Tags:

c

enums

In C, is there a nice way to track the number of elements in an enum? I've seen

enum blah {     FIRST,     SECOND,     THIRD,     LAST }; 

But this only works if the items are sequential and start at zero.

like image 629
Peter Gibson Avatar asked Apr 03 '09 03:04

Peter Gibson


People also ask

How do you find the number of elements in an enum?

Enum.GetNames(typeof(INFORMATION)).Count() It will be helpful. Even though you will increase decrease values in enum It will give correct result.

Why is enum size 4?

The size is four bytes because the enum is stored as an int . With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

How many values can enum hold?

An ENUM column can have a maximum of 65,535 distinct elements. If you retrieve an ENUM value in a numeric context, the column value's index is returned.


2 Answers

If you don't assign your enums you can do somethings like this:

enum MyType {   Type1,   Type2,   Type3,   NumberOfTypes } 

NumberOfTypes will evaluate to 3 which is the number of real types.

like image 105
vpicaver Avatar answered Sep 19 '22 08:09

vpicaver


I don't believe there is. But what would you do with such a number if they are not sequential, and you don't already have a list of them somewhere? And if they are sequential but start at a different number, you could always do:

enum blah {     FIRST = 128,     SECOND,     THIRD,     END }; const int blah_count = END - FIRST; 
like image 29
Brian Campbell Avatar answered Sep 21 '22 08:09

Brian Campbell