Skip to content

[C] Introduction of Symbolic Constants

Last Updated on 2021-04-29 by Clay

Use Symbolic Constants is a way to improve the "source code readability". Just like the classic conversion between Celsius and Fahrenheit, the lower, upper, and step of the boundary value and the updated value are actually meaningful numbers, especially the temperature boundary value.

Such a magical but important value, we will call it magic number. In the program, if third-party developers who do not understand the situation cam understand the importance of this value at a glance, we can write it as a Symbolic Constant.


How to use Symbolic Constant

The setting of symbolic constants needs to be written at the beginning of the program, under the description of #include library, etc.

#define NAME REPLACEMENT_TEXT

After that, the compiler will automatically treat it as the value of REPLACEMENT_TEXT every time it parses the name of NAME. You might want to ask: Is this different from using variables?

Variables can be reassigned, but symbolic constants cannot.

Suppose we set X to 100.

#define X 100

We can't set X to another value again:

# Error
X = 200;

This will report an error, because in the understanding of the compiler, this program is as follows:

100 = 200;

Obviously wrong.

Next, we rewrite again the code for converting between Celsius and Fahrenheit, which was rewritten using the for-loop in the previous note.

#include <stdio.h>

#define LOWER 0
#define UPPER 300
#define STEP 20


int main() {
    float F, C;

    // For-loop
    for (F=LOWER; F<=UPPER; F+=STEP) {
        C = (5.0 / 9.0) * (F - 32.0);
        printf("%3.0f %6.1f\n", F, C);
    }

    return 0;
}


Output:

  0  -17.8
 20   -6.7
 40    4.4
 60   15.6
 80   26.7
100   37.8
120   48.9
140   60.0
160   71.1
180   82.2
200   93.3
220  104.4
240  115.6
260  126.7
280  137.8
300  148.9


Finally, explain again the symbolic constants:

  • The purpose is to improve readability
  • It is constant, not a variable, and cannot be assigned.

References


Read More

Leave a Reply