23
Aug

C++ Tutorial – 21 – Enum


An enumeration is a user-defined type consisting
of a fixed list of named constants. For example, we here have an enum type called color containing
three constants – red, green, and blue. This Color type can now be used to create a variable
that can hold any one of these constant values. To assign one of them to the variable we can
simply type the name of the constant. In order to avoid naming conflicts we can also qualify
the constant with the name of the enum. The switch statement provides a good example
of when enumerations can be used. Compared to using ordinary constants the enumeration
has the advantage that it allows us to clearly specify what values a variable should contain. Usually, we don’t need to know the underlying
values that the constants represent, but in some cases it can be useful. By default, the
first constant in the enum list has the value 0 and each successive constant has one value
higher. We can override these default values by assigning
the constants to any values we want. These values can be computed and don’t have to
be unique. The compiler can implicitly convert an enumeration
constant to an integer. However, converting an integer back into an enum requires an explicit
cast since this conversion makes it possible to assign a value to the variable that is
not included in the enum list. Note that an enum does not have to be declared
globally. It can also be placed within a class as a class member or even be defined locally
in a function.

Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

There are no comments yet

Why not be the first

Leave a Reply

Your email address will not be published. Required fields are marked *