Declared constants allow you to create a variable that cannot be changed by using the const keyword in front of a variable declaration. This is good practice for numbers that do not change - assigning them to a constant insures that nothing in the program will ever change their value. If a statement attempts to change a constant's value, the compiler will show a syntax error.
#include <iostream> using namespace std; int main() { const float Pi = 3.1415; cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl; return 0; } |
Circumference of circle: 8.7962 |
The #define statement is a preprocessor directive to do a string substitution. This means that the substitution(s) are done before the code is compiled. At the top of your program, you can type:
#define Pi 3.1415
Inside the program, you can use it as if it were a declared constant:
cout << 2 * Pi * 1.4;
Anywhere your code has a reference to Pi, it is replaced with 3.1415 before the program is compiled. The following program demonstrates using a defined constant.
#include <iostream> using namespace std; #define Pi 3.1415 int main() { cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl; return 0; } |
Circumference of circle: 8.7962 |
In most cases, using declared constants (const statement) is preferred over defined constants since the former has a variable type to associate with. Also, defined constants are global and could potentially be a problem in large projects.
The enum keyword allows you to create a new type with a defined set of values. The following line declares a new type named CarTypes and defines its possible values:
enum CarTypes {Corvette, Mustang, Viper, Ferrari, Lamborghini};
You can use this new type (CarTypes) similarly to a variable type. The next program declares the enumerated CarTypes, and then declares two variables of this type (Car1 and Car2). This program uses an if statement which is covered in Chapter 9.
#include <iostream> using namespace std; int main() { enum CarTypes {Corvette, Mustang, Viper, Ferrari, Lamborghini}; CarTypes Car1 = Corvette; CarTypes Car2 = Ferrari; if (Car1 == Corvette) cout << "Wise Choice!\n"; return 0; } |
Wise Choice! |
Enumerated types have an integer value. In the previous program, Corvette = 0, Mustang = 1, Viper = 2, Ferrari = 3, and Lamborghini = 4. Therefore, doing the following would assign the value of 7 to the integer MyCars:
int MyCars = Ferrari + Lamborghini;
You can assign your own values to enumerated types by doing the following:
enum CarTypes {Corvette=1, Mustang=5, Viper=10, Ferrari