14 More on Data Types
14 More on Data Types
THIS CHAPTER INTRODUCES YOU TO Adata type that has not yet been described: the
enumerateddata type.You also learn about the typedefstatement, which enables you to
assign your own names to basic data types or to derived data types. Finally, in this chap-
ter you see the precise rules that are used by the compiler in the conversion of data types
in an expression.
Enumerated Data Types
Wouldn’t it be nice if you could define a variable and specify the valid values that could
be stored into that variable? For example, suppose you had a variable called myColorand
you wanted to use it to store one of the primary colors,red,yellow, or blue, and no
other values.This type of capability is provided by the enumerated data type.
An enumerated data type definition is initiated by the keyword enum.Immediately
following this keyword is the name of the enumerated data type, followed by a list of
identifiers (enclosed in a set of curly braces) that define the permissible values that can
be assigned to the type. For example, the statement
enum primaryColor { red, yellow, blue };
defines a data type primaryColor.Variables declared to be of this data type can be
assigned the values red,yellow,and blueinside the program,and no other values.That’s
the theory anyway! An attempt to assign another value to such a variable causes some
compilers to issue an error message. Other compilers simply don’t check.
To declare a variable to be of type enum primaryColor,you again use the keyword
enum, followed by the enumerated type name, followed by the variable list. So the
statement
enum primaryColor myColor, gregsColor;