Like variables, constants are named data-storage locations. However, unlike a variable, the value of a constant can’t be changed after it has been declared. It has to be initialized when it’s created and can’t be assigned a new value later. C++ has two types of constants: literal and symbolic.
A literal constant is simply a value typed into the program. The statements in the following code assign the literals 40 and Dog to the respective variables NoOfEmployees and strName:
NoOfEmployees = 40; strName = "Dog";
A symbolic constant is a constant that is represented by a name. It is defined in exactly the same way as a variable, but the qualifier must start with the keyword const and the variable must be initialized. After declaration, the constant name can be used anywhere a variable of that type can be used, as shown here:
const unsigned long NoOfFullTimeEmployees = 49; const unsigned long NoOfPartTimeEmployees = 234; unsigned int NoOfEmployees; NoOfEmployees = NoOfFullTimeEmployees + NoOfPartTimeEmployees;
There are a couple of advantages to using symbolic constants rather than literal ones:
The symbolic names make the program more readable. The symbolic constant NoOfFullTimeEmployees is more meaningful than the literal constant 49.
It’s easier to change a single symbolic constant declaration than to find and replace all occurrences of a literal in a program.
However, using symbolic constants instead of literals can be taken too far. It is not necessary to replace all literals with constants. There are some constants that are intuitively obvious to everyone and that are not going to change; for example, the number of days in a week or months in a year. These values can be left as literals without reducing the readability or maintainability of the code.