|
||||||
C++ constants are values used in a program and will not change during the operation of the program and are important for any programmer in the operation of their programs
C++ constants are not very different from any C++ variable. They are defined in a similar way and have the same data types and the same memory limitations. However, there is one major difference - once a constant has been created and value assigned to it then that value may not be changed. Defining Constants with C++There are actually three ways of defining a constant in a C++ program:
It's also worth noting that there are two types of constant: literal and symbolic. Literal and Symbolic ConstantsA literal constant is simply a value used directly in a block of code, for example: circumference = 2 * 3.14 * r;
area = 3.14 * r * r;
Here 2 and 3.14 (pi to 2 decimal places) are literal constants. However, there is an obvious disadvantage to using literal constants. If the constant needs to be changed (for example changing pi to 4 decimal places) then the programmer will have to manually change all instances of the constant themselves. It is therefore often more practical to use symbolic constants:
circumference = 2 * pi_val * r;
area = pi_val * r * r;
Now the value of the constant only needs to be defined once.
Defining C++ Constants with the Preprocessor
The preprocessor is run before the program is compiled. It will look for any lines starting with a hash (#) and will then modify the code according to what it finds. An example of a constant defined in the preprocessor is:
#define pi_val 3.1416
const float pi_val = 3.1416;
enum DAY {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};
#include
enum DAY {MONDAY = 1, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};
int main () {
int day;
cout << "Enter day number: ";
cin >> day;
if ((day == SATURDAY) || (day == SUNDAY)) {
cout << "Weekend"; }
else if ((day >= MONDAY) && (day <= FRIDAY)) {
cout << "Working Day";
} else {
cout << "Invalid Number";
}
return 0;
}
The copyright of the article How to Use C++ Constants in C Programming is owned by Mark Alexander Bain. Permission to republish How to Use C++ Constants in print or online must be granted by the author in writing.
|
||||||
|
|
||||||
|
|
||||||