4.3: Constants and Variables
- Page ID
Various textbooks describe constants using different terminology. Added to the complexity are the explanations from various industry professionals will vary greatly. Let's see if we can clear it up.
A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies – their value is constant.
A variable is a data item whose value can change during the program's execution. Thus, as its name implies – their value can vary.
Constants are used in three ways within C++. They are:
- literal constant
- defined constant
- memory constant
A literal constant is a value you type into your program wherever it is needed. Examples include the constants used for initializing a variable and constants used in lines of code:
Literal Constants int age = 21; char grade = 'A'; float money = 12.34; bool rich = false; cout << "\nStudents love computers"; age - 57;
Additionally, we have learned how to recognize the data types of literal constants. Single quotes for char, double quotes for string, number without a decimal point for integer, number with a decimal point belongs to the floating-point family, and Boolean can use the reserved words of true or false.
In addition to literal constants, most text books refer to either symbolic constants or named constants but these two refer to the same concept. A symbolic constant is represented by a name similar to how we name variables. Let's say it backwards; the identifier name is the symbol that represents the data item. Within C++ identifier names have some rules. One of the rules says those names should be meaningful. Another rule about using ALL CAPS FOR CONSTANTS is an industry rule. There are two ways to create symbolic or named constants:
#define PI 3.14159
Called a defined constant because it uses a textual substitution method controlled by the compiler pre-processor command word "define".
const double PI = 3.14159;
The second one is called sometimes called constant variable but that name is contradictory all by itself. How can it be constant and vary at the same time? The better name for the second one is a memory constantbecause they have a "specific storage location in memory".
Defining Constants and Variables
In the above examples we see how to define both variables and constants along with giving them an initial value. Memory constants must be assigned a value when they are defined. But variables do not have to be assigned initial values.
Variables once defined may be assigned a value within the instructions of the program.
height = 72;
value_coins = 2 * 0.25 + 3 * 0.05;
- A data item whose value cannot change during the program's execution.
- A data item whose value can change during the program's execution.