Constants and aliases

Previous Index Next

Constants Aliases

Constants Top

A constant declaration statement is similar to a variable declaration and initialisation statement, except that the reserved word const is added in front of the statement in constant declaration. For example:

C++ statements Equivalent Pascal statements
const float x = 3.7; const x = 3.7;
const int a = 4, b = 7; const
  a = 4;
  b = 7;

Note that the value of a constant cannot be modified.


Aliases Top

An alias is a name (usually more meaningful, easier to remember or type) used in a program. Before compilation, the alias will be translated into another name or string (usually less meaningful, less easy to remember or type).

We can use #define preprocessor directives to define an alias. For example, the statement
    #define MAX 100
defines an alias called MAX which is identical to 100. During compile time, any occurrence of MAX in the program will be replaced by 100:

#include <iostream.h>
#define MAX 100
  ...
int a[
MAX];
  ...

for (i = 0; i <
MAX; i++)
  ...
if (n >=
MAX * 2)
  ...
... is translated to ... #include <iostream.h>

  ...
int a[
100];
  ...

for (i = 0; i <
100; i++)
  ...
if (n >=
100 * 2)
  ...

As you can see, #define preprocessor directives can be used to define constants. But the main differences between using const and using #define is that the const statement tells the program to allocate some memory space to store the constant, while the aliases defined by the #define preprocessor directives are not stored in memory; they are translated to their original name during compilation.

In fact, most C++ programmers prefer using #define preprocessor directives to define constants.

See Program 24 for a program using #define preprocessor directives.

Previous Index Next