- Symbolic Constant
- A symbolic constant is a label (name) that represents a fixed value that never changes during the course of a program.
What Are Constants?
Symbolic constants are what most people think of when someone refers to "constants" in any programming language. Symbolic constants are nothing more than a label or name that is used to represent a fixed value that never changes throughout a program. For example, one might define PI as a constant to represent the value 3.14159.
Why Do We Need Constants?
Avoid Magic Numbers
Magic numbers are literals that get used in your code without any obvious reason. For example, if I have a line of code like:
Why is the value of 0x30 used here? Why not 0x31 or 0xBEEF? What is the significance of that particular value? Only the programmer knows, and he has likely forgotten. A better approach is to build a description into the value by creating a named/symbolic constant and using it in place of the raw value:
Where ASCII_OFFSET is defined somewhere in the program to have a value of 0x30.
Even if you don't know what is meant by ASCII_OFFSET, you at least have some clue as to what its purpose is so you can ask the right questions.
Quickly Change Values During Development
When developing a complex program, there may be situations where you need to calibrate or otherwise tweak your constant values until the system works the way you expect. For example, say you have a delay routine used all over your program that you need to play with to get the timing right before releasing your code. If you load a counter register with a value like 255 everywhere you use the delay, it would be very cumbersome to change the value in multiple locations. If on the other hand, you create a constant called DELAY_COUNT and use it everywhere you use the delay, changing the value is as easy as changing the constant's definition.
How to Define Constants
There are two ways to create constants in C that we will look at over the next two pages: