20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

14<br />

More on Data Types<br />

THIS CHAPTER INTRODUCES YOU TO A data type that has not yet been described: the<br />

enumerated data type.You also learn about the typedef statement, which enables you to<br />

assign your own names to basic data types or to derived data types. F<strong>in</strong>ally, <strong>in</strong> this chapter<br />

you see the precise rules that are used by the compiler <strong>in</strong> the conversion of data types<br />

<strong>in</strong> an expression.<br />

Enumerated Data Types<br />

Wouldn’t it be nice if you could def<strong>in</strong>e a variable and specify the valid values that could<br />

be stored <strong>in</strong>to that variable? For example, suppose you had a variable called myColor and<br />

you wanted to use it to store one of the primary colors, red, yellow, or blue, and no<br />

other values.This type of capability is provided by the enumerated data type.<br />

An enumerated data type def<strong>in</strong>ition is <strong>in</strong>itiated by the keyword enum.Immediately<br />

follow<strong>in</strong>g this keyword is the name of the enumerated data type, followed by a list of<br />

identifiers (enclosed <strong>in</strong> a set of curly braces) that def<strong>in</strong>e the permissible values that can<br />

be assigned to the type. For example, the statement<br />

enum primaryColor { red, yellow, blue };<br />

def<strong>in</strong>es a data type primaryColor.Variables declared to be of this data type can be<br />

assigned the values red, yellow,and blue <strong>in</strong>side the program, and no other values.That’s<br />

the theory anyway! An attempt to assign another value to such a variable causes some<br />

compilers to issue an error message. Other compilers simply don’t check.<br />

To declare a variable to be of type enum primaryColor,you aga<strong>in</strong> use the keyword<br />

enum, followed by the enumerated type name, followed by the variable list. So the<br />

statement<br />

enum primaryColor myColor, gregsColor;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!