Thứ Hai, 3 tháng 3, 2014

Tài liệu Module 5 pptx


5
C++ A Beginner’s Guide by Herbert Schildt



1. When a function is called, what happens to program execution?
2. What is the difference between an argument and a parameter?
3. If a function requires a parameter, where is it declared?
CRITICAL SKILL 5.4: Using return
In the preceding examples, the function returned to its caller when its closing curly brace was
encountered. While this is acceptable for many functions, it won’t work for all. Often, you will want to
control precisely how and when a function returns. To do this, you will use the return statement.
The return statement has two forms: one that returns a value, and one that does not. We will begin with
the version of return that does not return a value. If a function has a void return type (that is, if the
function does not return a value), then it can use this form of return:
return;
When return is encountered, execution returns immediately to the caller. Any code remaining in the
function is ignored. For example, consider this program:


The output from the program is shown here:

6
C++ A Beginner’s Guide by Herbert Schildt


Introducing Functions
Before call
Inside f()
After call

As the output shows, f( ) returns to main( ) as soon as the return statement is encountered. The second
cout statement is never executed.
Here is a more practical example of return. The power( ) function shown in the next program displays
the outcome of an integer raised to a positive integer power. If the exponent is negative, the return
statement causes the function to terminate before any attempt is made to compute the result.


The output from the program is shown here:
The answer is: 100
When exp is negative (as it is in the second call), power( ) returns, bypassing the rest of the function.
A function may contain several return statements. As soon as one is encountered, the function returns.
For example, this fragment is perfectly valid:

7
C++ A Beginner’s Guide by Herbert Schildt



Be aware, however, that having too many returns can destructure a function and confuse its meaning. It
is best to use multiple returns only when they help clarify a function.
Returning Values
A function can return a value to its caller. Thus, a return value is a way to get information out of a
function. To return a value, use the second form of the return statement, shown here:
return value;
Here, value is the value being returned. This form of the return statement can be used only with
functions that do not return void.
A function that returns a value must specify the type of that value. The return type must be compatible
with the type of data used in the return statement. If it isn’t, a compile-time error will result. A function
can be declared to return any valid C++ data type, except that a function cannot return an array.
To illustrate the process of functions returning values, the box( ) function can be rewritten as shown
here. In this version, box( ) returns the volume. Notice that the placement of the function on the right
side of an assignment statement assigns the return value to a variable.

8
C++ A Beginner’s Guide by Herbert Schildt



Here is the output:
The volume is 330
In this example, box( ) returns the value of length * width * height using the return statement. This value
is then assigned to answer. That is, the value returned by the return statement becomes box( )’s value in
the calling routine.
Since box( ) now returns a value, it is not preceded by the keyword void. (Remember, void is only used
when a function does not return a value.) Instead, box( ) is declared as returning a value of type int.
Notice that the return type of a function precedes its name in both its prototype and its definition.
Of course, int is not the only type of data a function can return. As stated earlier, a function can return
any type of data except an array. For example, the following program reworks box( ) so that it takes
double parameters and returns a double value:

9
C++ A Beginner’s Guide by Herbert Schildt



Here is the output:
The volume is 373.296
One more point: If a non-void function returns because its closing curly brace is encountered, an
undefined (that is, unknown) value is returned. Because of a quirk in the formal C++ syntax, a non-void
function need not actually execute a return statement. This can happen if the end of the function is
reached prior to a return statement being encountered. However, because the function is declared as
returning a value, a value will still be returned—even though it is just a garbage value. Of course, good
practice dictates that any non-void function that you create should return a value via an explicit return
statement.
CRITICAL SKILL 5.5: Using Functions in Expressions
In the preceding example, the value returned by box( ) was assigned to a variable, and then the value of
this variable was displayed via a cout statement. While not incorrect, these programs could be written
more efficiently by using the return value directly in the cout statement. For example, the main( )
function in the preceding program can be written more efficiently like this:

10
C++ A Beginner’s Guide by Herbert Schildt



When the cout statement executes, box( ) is automatically called so that its return value can be
obtained. This value is then output. There is no reason to first assign it to some variable.
In general, a non-void function can be used in any type of expression. When the expression is evaluated,
the function is automatically called so that its return value can be obtained. For example, the following
program sums the volume of three boxes and then displays the average volume:


The output of this program is shown here:
The sum of the volumes is 812.806 The average volume is 270.935

11
C++ A Beginner’s Guide by Herbert Schildt



1. Show the two forms of the return statement.

2. Can a void function return a value?

3. Can a function call be part of an expression?

Scope Rules
Up to this point, we have been using variables without formally discussing where they can be declared,
how long they remain in existence, and what parts of a program have access to them. These attributes
are determined by the scope rules defined by C++.
In general, the scope rules of a language govern the visibility and lifetime of an object.
Although C++ defines a finely grained system of scopes, there are two basic ones: local and global. In
both of these scopes, you can declare variables. In this section, you will see how variables declared in a
local scope differ from variables declared in the global scope, and how each relates to the function.
CRITICAL SKILL 5.6: Local Scope
A local scope is created by a block. (Recall that a block begins with an opening curly brace and ends with
a closing curly brace.) Thus, each time you start a new block, you are creating a new scope. A variable
can be declared within any block. A variable that is declared inside a block is called a local variable.
A local variable can be used only by statements located within the block in which it is declared. Stated
another way, local variables are not known outside their own code blocks.
Thus, statements defined outside a block cannot access an object defined within it. In essence, when
you declare a local variable, you are localizing that variable and protecting it from unauthorized access
and/or modification. Indeed, the scope rules provide the foundation for encapsulation.
One of the most important things to understand about local variables is that they exist only while the
block of code in which they are declared is executing. A local variable is created when its declaration
statement is encountered within its block, and destroyed when the block is left. Because a local variable
is destroyed upon exit from its block, its value is lost. The most common code block in which variables
are declared is the function. Each function defines a block of code that begins with the function’s
opening curly brace and ends with its closing curly brace. A function’s code and data are private to that
function and cannot be accessed by any statement in any other function except through a call to that
function. (It is not possible, for instance, to use a goto statement to jump into the middle of another
function.)

12
C++ A Beginner’s Guide by Herbert Schildt


The body of a function is hidden from the rest of the program, and it can neither affect nor be affected
by other parts of the program. Thus, the contents of one function are completely separate from the
contents of another. Stated another way, the code and data that are defined within one function cannot
interact with the code or data defined in another function, because the two functions have a different
scope. Because each function defines its own scope, the variables declared within one function have no
effect on those declared in another—even if those variables share the same name.
For example, consider the following program:


Here is the output:
val in main(): 10 val in f1(): 88 val in main(): 10
An integer called val is declared twice, once in main( ) and once in f1( ). The val in main( ) has no bearing
on, or relationship to, the one in f1( ). The reason for this is that each val is known only to the function in
which it is declared. As the output shows, even though the val declared in f1( ) is set to 88, the content
of val in main( ) remains 10.
Because a local variable is created and destroyed with each entry and exit from the block in which it is
declared, a local variable will not hold its value between activations of its block. This is especially
important to remember in terms of a function call. When a function is called, its local variables are
created. Upon its return, they are destroyed. This means that local variables cannot retain their values
between calls.

13
C++ A Beginner’s Guide by Herbert Schildt


If a local variable declaration includes an initializer, then the variable is initialized each time the block is
entered. For example:


The output shown here confirms that num is initialized each time f( ) is called:
99 99 99
A local variable that is not initialized will have an unknown value until it is assigned one.
Local Variables Can Be Declared Within Any Block
It is common practice to declare all variables needed within a function at the beginning of that
function’s code block. This is done mainly so that anyone reading the code can easily determine what
variables are used. However, the beginning of the function’s block is not the only place where local
variables can be declared. A local variable can be declared anywhere, within any block of code. A
variable declared within a block is local to that block. This means that the variable does not exist until
the block is entered and is destroyed when the block is exited. Furthermore, no code outside that
block—including other code in the function— can access that variable. To understand this, try the
following program:

14
C++ A Beginner’s Guide by Herbert Schildt




The variable x is declared at the start of main( )’s scope and is accessible to all subsequent code within
main( ). Within the if block, y is declared. Since a block defines a scope, y is visible only to other code
within its block. This is why outside of its block, the line
y = 100;
is commented out. If you remove the leading comment symbol, a compile-time error will occur, because
y is not visible outside of its block. Within the if block, x can be used because code within a block has
access to variables declared by an enclosing block.
Although local variables are typically declared at the beginning of their block, they need not be. A local
variable can be declared anywhere within a block as long as it is declared before it is used. For example,
this is a perfectly valid program:

Xem chi tiết: Tài liệu Module 5 pptx


Không có nhận xét nào:

Đăng nhận xét