Constant Variable s

The term constant variable might seem like a contradiction. After all, a constant never changes and a variable holds values that change. In C++ terminology, you can declare variables to be con- stants with the const keyword. Throughout your program, the constants act like variables; you can use a constant variable any- where you can use a variable, but you cannot change constant variables. To declare a constant, put the keyword const in front of the variable declaration, for instance:

const i nt days_of _week = 7;

C++ offers the const keyword as an improvement of the #def i ne preprocessor directive that C uses. Although C++ supports #def i ne as well, const enables you to specify constant values with specific data types.

Constant Variable s - 图1The const keyword is appropriate when you have data that does not change. For example, the mathematical π is a good candi- date for a constant. If you accidently attempt to store a value in a constant, C++ will let you know. Most C++ programmers choose to type their constant names in uppercase characters to distinguish them from regular variables. This is the one time when uppercase reigns in C++.

Example

Constant Variable s - 图2Suppose a teacher wanted to compute the area of a circle for the class. To do so, the teacher needs the value of π (mathematically, π is approximately 3.14159). Because π remains constant, it is a good candidate for a const keyword, as the following program shows:

EXAMPLE

Constant Variable s - 图3Comment for the program filename and description.

Declare a constant value for π*. Declare variables for radius and area.*

Compute and print the area for both radius values.

/ / Fil ename: C4AREAC. CPP

Constant Variable s - 图4/ / Comput es a ci r cl e wi t h r adi us of 5 and 20. #i ncl ude <i ost r eam. h>

mai n( )

{

const f l oat PI =3. 14159; f l oat r adi us = 5;

f l oat ar ea;

ar ea = r adi us * r adi us * PI ; / / Ci r cl e ar ea cal cul at i on cout << “ The ar ea i s “ << ar ea << “ wi t h a r adi us of 5.\ n” ;

r adi us = 20; / / Comput e ar ea wi t h new r adi us. ar ea = r adi us * r adi us * PI;

cout << “ The ar ea i s “ << ar ea << “ wi t h a r adi us of 20.\ n” ;

r et ur n 0;

}