You seem to need a good C++ book.
Enumerations, in C and C++, are a convenient way to:
- map an integral value to a "smart" name
- group together values that belong together
The syntax is quite simple (in C++03):
enum <enum-name> {
<value-name-0> [= <value-0>],
<value-name-1> [= <value-1>],
...
};
Where:
<enum-name>
is the name of the type that is introduced
<value-name-X>
is the name of a value of the enum
<value-X>
is the value given to the name, and is optional
If no value is given to a name:
- if it is the first, it is set to
0
- else, it is set to the value of the previous name,
+ 1
Here is a small example demonstrating the use of enums:
enum Color {
Blue,
Green,
Red
};
char const* name(Color c) {
switch(c) {
case Blue: return "Blue";
case Green: return "Green";
case Red: return "Red";
}
assert(0 && "Who stored crap in my enum ?");
}
This illustrates a few important points at once:
Color
is a type, like a struct type or a class type. It can be typedefed and all.
- an
enum
"value-name" is an integral constant, it can be used as template parameter or in switch cases.
- an
enum
"value-name" is injected in the scope in which the type is declared, and not nested within. (C++11 allows to scope the values with the enum class
syntax)
- something else entirely could be stored in the
enum
, while this should not happen in well behaved applications, you can do it through casting...
What is not shown, is that an enum
is under the hood a plain integer. The exact underlying type though is determined at the discretion of the compiler. There are a few rules in this choice, that should not matter to you, all you should know is that the type chosen is wide enough to contain all the values of the enum (and possibly signed if required). What it implies is that the type chosen is not necessarily a plain int
.
Therefore: printf("%d", Green);
is a programming error. It should be printf("%d", (int)Green);
.
Another important point, is that enum names do not appear in the final binary. The names are substituted for their values directly, no runtime overhead at all. Debuggers typically retrieve the names from the debug information (if available) and substitute them back in when presenting the information to you.