tags:

views:

97

answers:

5

I have an enum declaration as:

enum qty { cars = 10, bikes = 9, horses = 9 ... } // total 28

How could I add up all the associated values of enumerator-list?

+3  A: 

There is no way to express "for all enums in qty" in C.

msw
+5  A: 

You can't know at runtime the contents of an enum in C.

Besides, this sounds like a misuse of enumerations. You should use them to define constants that you will use inside your code, not to store quantities or stuff like that which should otherwise be variable: enumeration values are immutable. Use integer arrays for that purpose; you can loop through these.

zneak
+1  A: 

There's no way to loop thru them in C (you could in Ada ;-) so this is all you can do:

int sum = cars + bikes + horses + ...;

but like zneak and Tyler said, you're probably not using the right construct.

progrmr
+1  A: 

In C, enums are just mapped to integers. They're not even typesafe, as you can freely substitute members of one enum in places intended for other enums.

JustJeff
A: 

If you've got an awful lot of these to keep in sync then some preprocessor abuse might come in handy:

#define SUM(name, count) + (count)
#define DEF(name, count) name = (count),

enum qty
{
#   define QTY(f) \
    f(cars,  10)  \
    f(bikes,  9)  \
    f(horses, 9)

    QTY(DEF)

    total = 0 + QTY(SUM)
};
doynax