Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The usage of anonymous enums

Tags:

c++

enums

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.


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.


If this is old code, then enum might have been used for the "enum hack".

You can learn more about the "enum hack", for example, in this link: enum hack


One use of this is when you're doing template metaprogramming, because enum objects are not lvalues, while static const members are. It also used to be a common workaround for compilers that didn't let you initialize static integral constants in the class definition. This is explained in another question.


(1) int color = 1;

color is changeable (accidently).

(2) enum { color = 1 };

color cannot be changed.

The other option for enum is,

const int color = 1;  // 'color' is unmutable

Both enum and const int offer exactly same concept; it's a matter of choice. With regards to popular belief that enums save space, IMO there is no memory constraint related to that, compiler are smart enough to optimize const int when needed.

[Note: If someone tries to use const_cast<> on a const int; it will result in undefined behavior (which is bad). However, the same is not possible for enum. So my personal favorite is enum]


When you use
enum {color = 1}
you're not using any memory it's like
#define color 1

If you declare a variable
int color=1 Then you're taking up memory for a value that's not to be changed.