< previous page page_39 next page >

Page 39
This takes longer to type, but offers several advantages. The biggest difference is that this constant has a type, and the compiler can enforce that it is used according to its type.
Enumerated Constants
New Term: Enumerated constants create a set of constants with a range of values. For example, you can declare COLOR to be an enumeration; and you can define that there are five values for COLOR: RED, BLUE, GREEN, WHITE, and BLACK.
The syntax for enumerated constants is to write the keyword enum, followed by the type name, an open brace, each of the legal values separated by a comma, and finally a closing brace and a semicolon. Here's an example:
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };
This statement performs two tasks:
1. It makes COLOR the name of an enumeration, that is, a new type.
2. It makes RED a symbolic constant with the value 0, BLUE a symbolic constant with the value 1, GREEN a symbolic constant with the value 2, and so forth.
Every enumerated constant has an integer value. If you don't specify otherwise, the first constant will have the value 0, and the rest will count up from there. Any one of the constants can be initialized with a particular value, however, and those that are not initialized will count upward from the ones before them. Thus, if you write
enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };
then RED will have the value 100; BLUE, the value 101; GREEN, the value 500; WHITE, the value 501; and BLACK, the value 700.
Summary.
In this hour you learned about numeric and character variables and constants.
You must declare a variable before it can be used, and then you must store the type of data that you've declared correct for that variable. If you put too large a number into an integral variable, it produces an incorrect result.
This chapter also reviewed literal and symbolic constants, as well as enumerated constants, and showed two ways to declare a symbolic constant: using #define and using the keyword const.

 
< previous page page_39 next page >

If you like this book, buy it!