For the record, Bjarne Stroustrup talks about bringing enum
s into C++ in the book The Design and Exolution of C++ with the statement "C enumerations constitute a curiously half-baked concept. Enumerations were not part of the original conception of C and were apparently reluctantly introduced into the language as a concession to people who insisted on getting a form of symbolic constants more substantial than Cpp's parameterless macros." (section 11.7, "Cpp" refers to the C preprocessor, the rest of the section chronicles the decision to make each enum
a separate type in C++ instead of all of them being int
s as they originally were in C and early versions of C++).
enum
s are largely meant as a way of replacing #define
s in earlier versions of C.
// based on UNIX file permissions
#define EXECUTE 1
#define WRITE 2
#define READ 4
vs.
const int EXECUTE = 1;
const int WRITE = 2;
const int READ = 4;
vs.
enum File_perms {
EXECUTE = 1;
WRITE = 2;
READ = 4;
};
Which to use is largely a matter of personal taste. An enum
does provide a form of documentation about what kind of values a variable should hold:
int permissions = 4; // Was that file permissions, database permissions, or something else?
File_perms perms = 4;
This is especially helpful in function signatures:
int fiddle_bits(int, int); // I can never remember if I pass the file permissions as the first or second parameter ...
File_perms fiddle_bits2(File_perms, int);
enum
s are allowed in switch
statement case
labels (as are #define
s and const int
s):
switch (perm) {
case READ:
...
break;
...
}
However, note that it is possible to assign numbers to enum
s that don't have a labeled value (C++0x adds an enum class
that doesn't allow this):
File_perms perm = 7; // a.k.a., File_perms perm = EXECUTE | READ | WRITE;
If you ever see an enum
with explicit values that are powers of 2, you can almost guarantee that it will be used this way.