/* related posts with thumb nails */

Symbolic Constants:

We often use certain unique constants in a program. These constants may appear repeatedly in a number of places in the program. One example of such constant is 3.142, representing the value of the mathematical constant "pi". Another example is the total number of students that may be used for calculating the class total, class average, standard deviation, etc. We face two problems in the subsequent use of such programs. They are:

1. Problem in modification of the program.

2. Problem in understanding the program.

Modifiability: We may like to change the value of "pi" from 3.142 to 3.14159 to improve the accuracy of calculations. For this, we will have to search throughout the program and explicitly change the value of the constant wherever it has been used. If any value is left unchanged, the program may produce disastrous outputs.

Understandability: When a numeric value appears in a program, its use is not always clear, especially when the same value; means different things in different places. Assignment of a symbolic name to such constants frees us from these problems.

A constant is declared as follows:

1. Symbolic names take the same form as variable names. But, they are written in CAPITALS to visually distinguish them from normal variable names. This is only a convention, not a rule.

2. After declaration of symbolic constants, they should not be assigned any other value within the program by using an assignment statement. For example, STRENGTH = 200; is illegal.

3. Symbolic constants are declared for types. This is not done in C and C++ where symbolic constants are defined using the # define statement.

4. They can NOT be declared inside a method. They should be used only as class data members in the beginning of the class.


final float PI=3.14159

final int STRENGTH=50

Related Topics:


Post a Comment