Literals and constants in C++

Hard-coded values are often termed literals, and there are four main forms in C++:

The problem with hard-coded values is that they often appear multiple times in a program, and often need to be modified over time.

For instance, we might have a program that uses the value Pi in multiple locations. If we decide that 3.14 is an accurate enough representation then we might type that value directly into the code in all the locations it is needed.

Suppose later we decide that is isn't accurate enough - we modifiy the program to use 3.1415296, changing the old value in each location. If we accidentally make a typo in one spot, or forget to change one of the values, then the code may have unpredicatable or unexpected results.

Even worse, suppose we use Pi for different things in the program, sometimes needing one accuracy (3.14), sometimes the other (3.1415296). Then we can't even use a global search and replace to make sure we catch all the places a change is needed: we need to go through by hand and decipher the logic to make sure we get the correct change in each case. That is slow and error prone.

Constants: can be used to make this process more reliable and more efficient. Constants are similar to variables except that their value is fixed for the entire run of the program.

The syntax is to specify it is a constant, the data type, the name you are giving it, and the value to associate with the name, e.g.:

const float Pi = 3.14;
const float AccuratePi = 3.1415296;
We can then use the names, Pi and AccuratePi, throughout the code rather than hard-coding the literal values everywhere. If we decide to modify a value later only the constant definition needs to be changed, and then the correct value is automatically used everywhere within the code.

Constants also have the advantage of providing a meaningful name, rather than a possibly-obscure value within the code. Suppose we see a calculation like this:
v = p * 1.0525 * (1 - 0.03245) / 1.035;
That is far less intuitive to read/understand/debug than something with meaningful names, e.g.:
value = principal * InterestRate * (1 - TaxRate) / InflationRate;

#define statements in C++

There is also a C pre-processor statement, #define, that can be used for similar purposes:
#define Pi 3.14
(Note there is no = symbol and no semi-colon in the #define.)

Before compiling the rest of the code, the compiler goes through pre-processor statements (#include, #define, etc). In the case of #define statements it goes through the rest of the program and performs direct substitution of 3.14 everyplace it finds Pi.