UMBC CMSC 202
UMBC CMSC 202 CSEE | 202 | current 202

Symbolic Constants in C++

const variables

In many instances, it is desirable to define names for commonly used values that don't change. These names are known as "symbolic constants". In C we used the #define mechanism. Consider the following definition and functions #define PI 3.14159 double CircleArea( double radius ) { return PI * radius * radius; } double CircleCirumference ( double radius ) { return PI * radius; } When this code is compiled, the compiler's preprocessor searches the code for all occurrences of PI and replaces them with 3.14159, just like you might do with a text editor.

While C++ supports the #define mechanism, there is a better way. In C++, we would define PI as a variable that cannot be changed. Any attempt to change the variable PI results in a compiler error.

const double PI = 3.14159; This method is preferred over #define because
  1. We explicitly specify the actual type (double} of PI
  2. We can use C++ scoping rules to limit the definition of PI (more on this later)
  3. We can use const with more elaborate types such as arrays, and struct (and later classes)
  4. We can examine the value of the variable PI with our debugger.

Enumerations

An alternative to creating symbolic constants is the use of an enumeration. Enumerations are part of C as well as C++, but not covered in CMSC 201.

An enumeration (aka enum) allows you to define new data types, but in a limited way. Consider this definition.

enum DAYS { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }; This statement does two things
  1. It defines DAYS as a new data type (an enumeration)
  2. It establishes SUNDAY, MONDAY, ets as symbolic constants (enumerators)
We can now define variables of type DAYS just like any other variable. The difference is that only the enumerators (SUNDAY, MONDAY, etc) may be assigned to those variables. DAYS weekend; weekend = FRIDAY; // okay weekend = 42; // compiler error The variable "weekend" is limited only to 7 variables - the enumerators. In general, arithmetic operators are not permitted on enumerations.


Last Modified: Monday, 28-Aug-2006 10:15:54 EDT