Elementary Programming in C++: Named Constants

A named constant is an identifier that represents a permanent value.

The value of a variable may change during the execution of a program, but a named con­stant, or simply constant, represents permanent data that never changes. In our ComputeArea program, π is a constant. If you use it frequently, you don’t want to keep typing 3.14159; instead, you can declare a constant for π. Here is the syntax for declaring a constant:

const datatype CONSTANTNAME = value;

A constant must be declared and initialized in the same statement. The word const is a C++ keyword for declaring a constant. For example, you may declare π as a constant and rewrite Listing 2.2 as shown in Listing 2.4.

Listing 2.4  ComputeAreaWithConstant.cpp

1 #include <iostream>

2 using namespace std;

3

4 int main()

5 {

6    const double PI = 3.14159;

7

8    // Step 1: Read in radius

9     double radius;

10    cout << “Enter a radius: “;

11    cin >> radius;

12

13    // Step 2: Compute area

14    double area = radius * radius * PI;

15

16    // Step 3: Display the area

17    cout << “The area is “;

18    cout << area << endl;

19

20    return 0;

21 }

Source: Liang Y. Daniel (2013), Introduction to programming with C++, Pearson; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *