开发者

enum associated values in c

开发者 https://www.devze.com 2022-12-24 09:38 出处:网络
I have an enum declaration as: 开发者_JS百科enum qty { cars = 10, bikes = 9, horses = 9 ... } // total 28

I have an enum declaration as:

开发者_JS百科enum qty { cars = 10, bikes = 9, horses = 9 ... } // total 28

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


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.


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


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.


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.


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)
};
0

精彩评论

暂无评论...
验证码 换一张
取 消