Chapter 7 Constants

7.1  Declared Constants

Declared constants allow you to create a variable that cannot be changed.  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.  The following program demonstrates the use of a declared constant.

Program 7.1 Declared Constants

#include <iostream>

using namespace std;
int main()
{

  const float Pi = 3.1415;
  cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl;
 
  return 0;
}

Output
Circumference of circle: 8.7962

7.2  Defined Constants

The #define statement is a preprocessor directive to do a string substitution.  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.

Program 7.2 Defined Constants

#include <iostream>

using namespace std;

#define Pi 3.1415
int main()
{
  
cout << "Circumference of circle: " << 2 * Pi * 1.4 << endl;

   return 0;
}

Output
Circumference of circle: 8.7962

For most cases, using declared constants (const statement) is preferred over defined constants since the former has a variable type to associate with.

7.3  Enumerated Types

The enumeration command (enum) allows you to define 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.

Program 7.3 Enumerated Types

#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;
}

Output
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