Objective-C / C giving enums default values

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-20 12:34:17

问题


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.



来源:https://stackoverflow.com/questions/2832606/objective-c-c-giving-enums-default-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!