C++ – Explicitly define enum values, even if the default value is the same

ccode-qualitycode-reviewsenum

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?

Best Answer

This is very much a judgement call, but I would agree with you that explicit values are the way to go, plus a comment at the start explaining the significance of the explicit values.

As an example of a prominent project that is doing it this way, look at Clang's AST serialization. It uses a huge enum to define codes for all of its AST nodes, and the enum has explicit values.

That said, I also sympathize with the opinion of the architecture team that touching old code that works when there's more important things to be done is not the best idea.

I don't like the compromise solution, though. It adds nothing.

Related Topic