Although most of the world has adopted the metric system for weights and measures, some countries are stuck with imperial units. For example, when talking with friends in Europe about the weather, people in the United States might have to convert from Celsius to Fahrenheit and back. Or they might want to convert height in inches to centimeters. We can write a program to help:
This code works correctly, but it has a minor problem. If another programmer reads this code, they might wonder where 2.54 comes from. For the benefit of others (and yourself in the future), it would be better to assign this value to a variable with a meaningful name. A value that appears in a program, like the number 2.54, is called a literal. In general, thereβs nothing wrong with literals. But when numbers like 2.54 appear in an expression with no explanation, they make the code hard to read. And if the same value appears many times and could change in the future, it makes the code hard to maintain.
Values like 2.54 are sometimes called magic numbers. The implication is that βmagicβ is not a good thing. A reader who doesnβt already know the conversion will look at the value 2.54 and feel like it appeared as if by magic.
A good practice is to avoid using magic numbers directly in calculations. Instead, assign them to variables with meaningful names and use those names in calculations:
double cmPerInch = 2.54;
double cm = inches * cmPerInch;
Now it is hopefully a little more clear what we are multiplying inches by and why. In addition, imagine we needed to use that value in 100βs of places in our code. If we ever need to change the value, we now only have to change it once where cmPerInch is set.
But we still have another problem. Variables can vary (hence the term), but the number of centimeters in an inch does not. Once we assign a value to cmPerInch, it should never change.
C++ provides the keyword const, a language feature that enforces this rule. When declaring a variable, you can add const before the type. This modifies the data type and declares that its canβt be changed after it is created. Trying to change a const value after it is created will result in a compile error as seen in this program:
const is not needed to make a program work correctly, but it does help prevent errors. It clearly communicates to other programmers that the value should not be changed and asks the compiler to enforce that rule.
Constants are often written in all capital letters to make them stand out. This is a convention, not a requirement. The following program demonstrates how many programmers would use a const to avoid the magic number 2.54:
Arrange the code to define a constant for the number of feet in a mile. Use the standard naming style for the name of the constant. You will not use all of the blocks.