The usage of anonymous enums
What is the purpose of anonymous enum
declarations such as:
enum { color = 1 };
Why not just declare int color = 1
?
Solution 1:
That's a so-called enum trick for declaring a compile-time integer constant. It's advantage is it guarantees that no variable is instantiated and therefore there's no runtime overhead. Most compilers introduce no overhead with integer constants anyway.
Solution 2:
Enums don't take up any space and are immutable.
If you used const int color = 1;
then you would solve the mutability issue but if someone took the address of color
(const int* p = &color;
) then space for it would have to be allocated. This may not be a big deal but unless you explicitly want people to be able to take the address of color
you might as well prevent it.
Also when declaring a constant field in a class then it will have to be static const
(not true for modern C++) and not all compilers support inline initialization of static const members.
Disclaimer: This answer should not be taken as advice to use enum
for all numeric constants. You should do what you (or your co-workers) think is more readable. The answer just lists some reasons one might prefer to use an enum
.