Objective-C / C giving enums default values

2019-03-19 15:16发布

问题:

I read somewhere about giving enums default values like so:

typedef enum  {
MarketNavigationTypeNone = 0,
MarketNavigationTypeHeirachy = 1,
MarketNavigationTypeMarket = 2
} MarketNavigationLevelType;

.. but i can't remember the value of doing this. If i don't give them default values - and then someone later on reorders the enum - what are the risks?

If i always use the enum name and don't even refer to them by their integer value, is there any risks?

The only possible problem i can think of is if i'm initialising an enum from an int value from a DB - and the enum is reordered - then the app would break.

回答1:

In general this only matters if the enum is exposed to some kind of external API or it is going to be used to exchange data via data files or other means. If the enum is only every used within your app and nowhere else then the actual values don't matter.



回答2:

That are not default values, you are giving them the values they will always have.

If you wouldn't initialize them explicitly, the first enumerators value is zero. For all others, if there is no initializer, their value is the value of the previous enumerator increased by one.

There are two reasons for giving them explicit values:

  • you don't want them to have the values they'd have otherwise
  • you want to make it clear what value they have (for you or other developers)

If you always refer to them by their name and never explicitly use an integral value for comparison or assignment, explicitly giving them a value is not needed.