Concepts of Programming Languages

(Sean Pound) #1

256 Chapter 6 Data Types


0 to represent blue, 1 to represent red, and so forth. These values could be
defined as follows:

int red = 0, blue = 1;

Now, in the program, we could use red and blue as if they were of a
color type. The problem with this approach is that because we have not
defined a type for our colors, there is no type checking when they are used.
For example, it would be legal to add the two together, although that would
rarely be an intended operation. They could also be combined with any
other numeric type operand using any arithmetic operator, which would
also rarely be useful. Furthermore, because they are just variables, they
could be assigned any integer value, thereby destroying the relationship
with the colors. This latter problem could be prevented by making them
named constants.
C and Pascal were the first widely used languages to include an enumera-
tion data type. C++ includes C’s enumeration types. In C++, we could have the
following:

enum colors {red, blue, green, yellow, black};
colors myColor = blue, yourColor = red;

The colors type uses the default internal values for the enumeration con-
stants, 0, 1,... , although the constants could have been assigned any integer
literal (or any constant-valued expression). The enumeration values are coerced
to int when they are put in integer context. This allows their use in any
numeric expression. For example, if the current value of myColor is blue,
then the expression

myColor++

would assign green to myColor.
C++ also allows enumeration constants to be assigned to variables of any
numeric type, though that would likely be an error. However, no other type
value is coerced to an enumeration type in C++. For example,

myColor = 4;

is illegal in C++. This assignment would be legal if the right side had been cast
to colors type. This prevents some potential errors.
C++ enumeration constants can appear in only one enumeration type in
the same referencing environment.
In Ada, enumeration literals are allowed to appear in more than one
declaration in the same referencing environment. These are called over-
loaded literals. The rule for resolving the overloading—that is, deciding
the type of an occurrence of such a literal—is that it must be determinable
Free download pdf