Like variables, constants are data storage locations. Unlike variables, and as the name implies, constants don't change. You must init...
Like variables, constants are data storage locations. Unlike variables, and as the name implies, constants don't change. You must initialize a constant when you create it, and you cannot assign a new value later.
C++ has two types of constants: literal and symbolic.
A literal constant is a value typed directly into your program wherever it is needed. For example
int myAge = 39;
myAge is a variable of type int; 39 is a literal constant. You can't assign a value to 39, and its value can't be changed.
A symbolic constant is a constant that is represented by a name, just as a variable is represented. Unlike a variable, however, after a constant is initialized, its value can't be changed.
If your program has one integer variable named students and another named classes, you could compute how many students you have, given a known number of classes, if you knew there were 15 students per class:
students = classes * 15;
NOTE: * indicates multiplication.
In this example, 15 is a literal constant. Your code would be easier to read, and easier to maintain, if you substituted a symbolic constant for this value:
students = classes * studentsPerClass
If you later decided to change the number of students in each class, you could do so where you define the constant studentsPerClass without having to make a change every place you used that value.
There are two ways to declare a symbolic constant in C++. The old, traditional, and now obsolete way is with a preprocessor directive, #define. Defining Constants with #define To define a constant the traditional way, you would enter this:
#define studentsPerClass 15
Note that studentsPerClass is of no particular type (int, char, and so on). #define does a simple text substitution. Every time the preprocessor sees the word studentsPerClass, it puts in the text 15.
Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15. Defining Constants with const Although #define works, there is a new, much better way to define constants in C++:
const unsigned short int studentsPerClass = 15;
This example also declares a symbolic constant named studentsPerClass, but this time studentsPerClass is typed as an unsigned short int. This method has several advantages in making your code easier to maintain and in preventing bugs. The biggest difference is that this constant has a type, and the compiler can enforce that it is used according to its type.
NOTE: Constants cannot be changed while the program is running. If you need to change studentsPerClass, for example, you need to change the code and recompile.
DON'T use the term int. Use short and long to make it clear which size number you intended. DO watch for numbers overrunning the size of the integer and wrapping around incorrect values. DO give your variables meaningful names that reflect their use. DON'T use keywords as variable names.
Enumerated Constants
Enumerated constants enable you to create new types and then to define variables of those types whose values are restricted to a set of possible 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.
You can define variables of type COLOR, but they can be assigned only one of the enumerated values (in this case, RED, BLUE, GREEN, WHITE, or BLACK, or else 100, 101, 500, 501, or 700). You can assign any color value to your COLOR variable. In fact, you can assign any integer value, even if it is not a legal color, although a good compiler will issue a warning if you do. It is important to realize that enumerator variables actually are of type unsigned int, and that the enumerated constants equate to integer variables. It is, however, very convenient to be able to name these values when working with colors, days of the week, or similar sets of values. Listing 3.7 presents a program that uses an enumerated type.
Listing 3.7. A demonstration of enumerated constants.
1: #include <iostream.h>
2: int main()
3: {
4: enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Â_Saturday };
5:
6: Days DayOff;
7: int x;
8:
9: cout << "What day would you like off (0-6)? ";
10: cin >> x;
11: DayOff = Days(x);
12:
13: if (DayOff == Sunday || DayOff == Saturday)
14: cout << "\nYou're already off on weekends!\n";
15: else
16: cout << "\nOkay, I'll put in the vacation day.\n";
17: return 0;
18: }
Output: What day would you like off (0-6)? 1
Okay, I'll put in the vacation day.
What day would you like off (0-6)? 0
You're already off on weekends!
Analysis: On line 4, the enumerated constant DAYS is defined, with seven values counting upward from 0. The user is prompted for a day on line 9. The chosen value, a number between 0 and 6, is compared on line 13 to the enumerated values for Sunday and Saturday, and action is taken accordingly.
The if statement will be covered in more detail in, "Expressions and Statements."
You cannot type the word "Sunday" when prompted for a day; the program does not know how to translate the characters in Sunday into one of the enumerated values.
NOTE: For this and all the small programs in this book, I've left out all the code you would normally write to deal with what happens when the user types inappropriate data. For example, this program doesn't check, as it would in a real program, to make sure that the user types a number between 0 and 6. This detail has been left out to keep these programs small and simple, and to focus on the issue at hand.