Saturday 4 April 2020

Symbolic Constants in C++


Symbolic Constants
There are two ways to create symbolic constants in C++:
  1. Using the qualifier constant and
  2. Defining a set of integer constants using enum keyword.
In both C and C++, any value declared as const cannot be modified by the program in anyway.  However, there are some differences in implementation.  In C++, we can use const in a constant expression, such as

     const int size =10;
     char name [size];

It is illegal in C. As with long and short, if we use the const modifier alone, it defaults to int.  For example,
                const size =10;
means      const int size =10;

The named constants are just like variables except their values cannot be changed.
C++ requires a const to be initialized.  In ANSI C, const values are global in nature.  They are visible outside the file in which they are declared.  However, they can be made local by declaring them as static.  To give a const value as external linkage so that it can be referenced from another file, we must explicitly define it as an extern in C++.
Example:
extern const total =100;
Another method of naming integer constants is as follows:
enum { X,Y,Z};
This defines X, Y and Z as integer constants with values 0,1 and 2 respectively.  This is equivalent to:
const X=0;
const Y=1;
const Z=2;
We can also assign values to X, Y and Z explicitly.
             enum{X=100, Y=50, Z=200};
such values can be any integer values.

No comments:

Post a Comment