3LET THE END BE LEGITIMATE, LET IT BE WITHIN THE SCOPE OF THE CONSTI...

3.3

Let the end be legitimate, let it be within the scope of the constitution, . . .John Marshall, Chief Justice U.S. Supreme Court,McCulloch v. Maryland (1803)

Functions should be self-contained units that do not interfere with other functions—

or any other code for that matter. To achieve this you often need to give the function

variables of its own that are distinct from any other variables that are declared outside

the function definition and that may have the same names as the variables that belong

to the function. These variables that are declared in a function definition are called local

variables and are the topic of this section.

LOCAL VARIABLES

Look back at the program in Display 3.1. It includes a call to the predefined function

sqrt

. We did not need to know anything about the details of the function definition

for

sqrt

in order to use this function. In particular, we did not need to know what vari-

ables were declared in the definition of

sqrt

. A function that you define is no different.

Variable declarations within a function definition are the same as if they were variable

declarations in a predefined function or in another program. If you declare a variable in

a function definition and then declare another variable of the same name in the

main

function of the program (or in the body of some other function definition), then these

two variables are two different variables, even though they have the same name. Let’s

look at an example.

The program in Display 3.8 has two variables named

averagePea

; one is declared

and used in the function definition for the function

estimateOfTotal

, and the other is

declared and used in the

main

function of the program. The variable

averagePea

in the

function definition for

estimateOfTotal

and the variable

averagePea

in the

main

func-

tion are two different variables. It is the same as if the function

estimateOfTotal

were

a predefined function. The two variables named

averagePea

will not interfere with

each other any more than two variables in two completely different programs would.

118 Function Basics

Display 3.8 Local Variables (part 1 of 2)