| Previous | Table of Contents | Next |
To define a constant the old-fashioned, evil, politically incorrect way, you would enter:
#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 15 in the text.
Because the preprocessor runs before the compiler, your compiler never sees your constant; it sees the number 15.
Although #define works, there is a new, better, less fattening, and more tasteful 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 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 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. Heres an example:
enum COLOR { RED, BLUE, GREEN, WHITE, BLACK };
This statement performs two tasks:
Every enumerated constant has an integer value. If you dont 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.
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 youve 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.
int aNumber = 5.4;
| Previous | Table of Contents | Next |