Search code examples
cenumsdeclarationexplicit

Should I explicitly define the values my enumerated constants


I've heard before that I should simply let the compiler choose which values to assign for enumerated constants if I'm not doing something clever like using the values as bitmasks. If I'm just using enumeration values for more explicit code documentation, are there any gotchas that could creep in if I don't explicitly define all the values? I believe that values are assigned in ascending order. Should I define the 1st value to ensure the same values for each successive compilation?


Solution

  • I think it will depend on your use of the type.

    Advantages to not providing enum initializers:

    • Easier to add and remove values as you develop.
    • You won't accidentally define two identifiers with the same value.

    Advantages to providing enum initializers:

    • Safe to serialize and deserialize the data. If you need to put these values in a file, network socket, etc., I would go ahead and write the values. (?)
    • Easier to look the values up for debugging purposes.