Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C / C giving enums default values

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.

like image 509
bandejapaisa Avatar asked May 14 '10 07:05

bandejapaisa


2 Answers

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.

like image 168
Georg Fritzsche Avatar answered Sep 18 '22 12:09

Georg Fritzsche


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.

like image 28
Paul R Avatar answered Sep 20 '22 12:09

Paul R