Programming in C

(Barry) #1

324 Chapter 14 More on Data Types


Program 14.1 Output
Enter month number: 5
Number of days is 31

Program 14.1 Output (Rerun)
Enter month number: 2
Number of days is 28
...or 29 if it’s a leap year

Enumeration identifiers can share the same value. For example, in
enum switch { no=0, off=0, yes=1, on=1 };
assigning either the value noor offto an enum switchvariable assigns it the value 0 ;
assigning either yesor onassigns it the value 1.
Explicitly assigning an integer value to an enumerated data type variable can be done
with the type cast operator. So if monthValueis an integer variable that has the value 6 ,
for example, the expression
thisMonth = (enum month) (monthValue - 1);
is permissible and assigns the value 5 to thisMonth.
When writing programs with enumerated data types, try not to rely on the fact that
the enumerated values are treated as integers. Instead, try to treat them as distinct data
types.The enumerated data type gives you a way to associate a symbolic name with an
integer number. If you subsequently need to change the value of that number, you must
change it only in the place where the enumeration is defined. If you make assumptions
based on the actual value of the enumerated data type, you defeat this benefit of using an
enumeration.
The variations permitted when defining an enumerated data type are similar to those
permitted with structure definitions:The name of the data type can be omitted, and
variables can be declared to be of the particular enumerated data type when the type is
defined. As an example showing both of these options, the statement
enum { east, west, south, north } direction;
defines an (unnamed) enumerated data type with values east,west,south, or north,
and declares a variable directionto be of that type.
Enumerated type definitions behave like structure and variable definitions as far as
their scope is concerned: Defining an enumerated data type within a block limits the
scope of that definition to the block. On the other hand, defining an enumerated data
type at the beginning of the program, outside of any function, makes the definition
global to the file.
When defining an enumerated data type, you must make certain that the enumeration
identifiers are unique with respect to other variable names and enumeration identifiers
defined within the same scope.
Free download pdf