Getting total number of enum items
13,628
An enum
is a plain-old-C type, therefore it provides no dynamic runtime information.
One alternative is to use the last element of an enum to indicate the count:
typedef enum {
Red,
Green,
Blue,
numColors
} Color;
Author by
Josh Buhler
Developer at Control4. If I'm not coding, I'm usually playing games, guitar, or out in the garage.
Updated on June 21, 2022Comments
-
Josh Buhler almost 2 years
Is it possible to get the total number of items defined by an enum at runtime?
While it's pretty much the same question as this one, that question relates to C#, and as far as I can tell, the method provided there won't work in Objective-C.
-
Ralph Sinsuat over 14 yearsGood for contiguous values, utterly fails for
typedef enum { Red=0xff0000, Green=0x00ff00, Blue=0x0000ff, numColors} Color;
. -
Josh Buhler over 14 yearsLike Mark said, this will fail big time for his example, the alternative provided by Darren is perfect for my needs. Thanks.
-
Ricardo Sanchez-Saez almost 10 yearsLook here for a better, completely automatic, but potentially dangerous solution: stackoverflow.com/q/24695580/269753