Reputation: 23
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?
Upvotes: 2
Views: 906
Reputation: 4465
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)
};
Upvotes: 0
Reputation: 12980
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.
Upvotes: 1
Reputation: 77291
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.
Upvotes: 1
Reputation: 138251
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.
Upvotes: 5