< previous page page_390 next page >

Page 390
As programs get larger and more complicated, the number of identifiers in a program increases. We invent function names, variable names, constant identifiers, and so on. Some of these identifiers we declare inside blocks. Other identifiersfunction names, for examplewe declare outside of any block. This chapter examines the C++ rules by which a function may access identifiers that are declared outside its own block. Using these rules, we return to the discussion of interface design that we began in Chapter 7.
Finally, we look at the second kind of subprogram provided by C++: the value-returning function. Unlike void functions, which return results (if any) through the parameter list, a value-returning function returns a single resultthe function valueto the expression from which it was called. In this chapter, you learn how to write user-defined value-returning functions.
Scope and Lifetime
Scope of Identifiers
As we saw in Chapter 7, local variables are those declared inside a block, such as the body of a function. Recall that local variables cannot be accessed outside the block that contains them. The same access rule applies to declarations of named constants: local constants may be accessed only in the block in which they are declared.
Any block, not only a function body, can contain variable and constant declarations. For example, this If statement contains a block that declares a local variable n:
if (alpha > 3)
{
    int n;

    cin >> n;
    beta = beta + n;
}
As with any local variable, n cannot be accessed by any statement outside the block containing its declaration.
If we list all the places from which an identifier could be accessed legally, we would describe that identifier's scope of visibility or scope of access, often just called its scope.
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif 3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
Scope The region of program code where it is legal to reference (use) an identifier.

 
< previous page page_390 next page >