There are times when an enum's values are important: it is not necessary for them to be unique, they also need to have specific values. In such cases, should the values be explicitly defined, even if they coincide with the defaults? An example:
enum Car {
DeLorean = 0,
Lada = 1
};
Imagine that for whatever reason your application assumes that DeLorean
and Lada
have those specific values. Incidentally, they are the same as the default values but does that mean it is no longer necessary to use explicit definitions?
Leaving them implicit makes me uneasy. It seams to me that having them explicitly defined is communicating to future programmers that the specific values are important and it helps prevent mistakes like this:
enum Car {
Dacia,
DeLorean,
Lada
};
In the example above, another programmer who is not aware of the restriction I mentioned introduces a new enum value and, wanting to keep the code tidy, puts it in alphabetical order. However, DeLorean
and Lada
now have different numerical values and a potentially silent bug has been introduced.
My reasoning seems correct to me (obviously), but the code review team for a company I used to work with didn't agree. Am I wrong?
enum Car { DeLorean = 0, Lada }
. I'm not sure that's much better, though.