Академический Документы
Профессиональный Документы
Культура Документы
C++ PROGRAMMING
• Review:
– Function as a procedural abstraction
– Predefined functions
– Scope rules
2
Objectives
• New to learn:
• Construct function headers and prototypes
• Return values from, and pass values to
functions
• Call by Value and Call by Reference
• Pass addresses to functions
• Pass arrays to functions
• Use default arguments
3
Using Functions and Include
Files
• Functions are modules that perform a task or group
of tasks
• Also called a subroutine, procedure, or method
• Write new C++ functions, and use functions that
other programmers have written
• Any statement allowed in the main( ) function of a C+
+ program can be used in any other function
4
The Function Call
• Back to this assignment:
theRoot = sqrt(9.0);
– The expression "sqrt(9.0)" is known as a
function call, or function invocation
– The argument in a function call (9.0) can be a
literal, a variable, or an expression
– The call itself can be part of an expression:
• bonus = sqrt(sales)/10;
• A function call is allowed wherever it’s legal to use
an expression of the function’s return type
3-5
Predefined Functions
• Libraries full of functions for our use!
• Two types:
– Those that return a value
– Those that do not (void)
• Must "#include" appropriate library
– e.g.,
• <cmath>, <cstdlib> (Original "C" libraries)
• <iostream> (for cout, cin)
3-6
Using Predefined Functions
• Math functions very plentiful
– Found in library <cmath.h>
– Most return a value (the "answer")
• Example: theRoot = sqrt(9.0);
– Components:
sqrt = name of library function
theRoot = variable used to assign "answer" to
9.0 = argument or "starting input" for function
– In I-P-O:
• I = 9.0
• P = "compute the square root"
• O = 3, which is returned & assigned to theRoot
3-7
Even More Math Functions:
Display 3.2 Some Predefined
Functions (1 of 2)
3-9
Predefined Void Functions
• No returned value
• Performs an action, but sends no "answer"
• When called, it’s a statement itself
– exit(1); // No return value, so not assigned
• This call terminates program
• void functions can still have arguments
• All aspects same as functions that "return
a value"
– They just don’t return a value!
3-10
Random Number Generator
• Return "randomly chosen" number
• Used for simulations, games
– rand()
• Takes no arguments
• Returns value between 0 & RAND_MAX
– Scaling
• Squeezes random number into smaller range
rand() % 6
• Returns random value between 0 & 5
– Shifting
rand() % 6 + 1
• Shifts range between 1 & 6 (e.g., die roll)
3-11
Random Number Seed
• Pseudorandom numbers
– Calls to rand() produce given "sequence"
of random numbers
3-12
Random Examples
Ex3-5.cpp
Ex3-6.cpp
• Random double between 0.0 & 1.0: Ex3-7.cpp
(RAND_MAX – rand())/static_cast<double>(RAND_MAX)
– Type cast used to force double-precision division
3-13
Understanding Scope
16
Using the Scope Resolution
Operator
• Each programmer can use x as a variable name
without destroying any values in the other’s function
• A major advantage of using local variables is that
many programmers can work on a large program,
each writing separate functions, and they can use
any variable names inside their own functions
• If you choose to create a global variable, you can
use it even when a local variable with the same name
exists
17
Using the Scope Resolution
Operator
• To do so, you use the scope resolution operator
• Place this operator (the symbol ::) directly before the variable
name
• Although you can declare global variables in any file, it is
almost always considered better style to use local variables
rather than global ones
18
Using the Scope Resolution
Operator
• This strategy represents a preliminary example of
encapsulation, or data hiding
• Using global variables, rather than creating local
variables in functions, is actually disadvantageous
for the following reasons:
– If variables are global in a file and you reuse any functions in a
new program, the variables must be redeclared in the new
program. They no longer “come along with” the function
– Global variables can be affected by any function, leading to
errors. In a program with many functions, finding the functions
that caused an error can prove difficult
19
Passing Values to Functions
20
Passing Values to Functions
21
Passing Values to Functions
Ex3-8.cpp
Ex3-9.cpp
Ex3-10.cpp
22
Objects as Arguments and Class as
Return Types
• A function can contain a variety of combinations of
actions
• Some functions contain local variables declared
within the function body
• Some functions return and receive nothing
• Others return values, receive values, or both
• Functions may receive any number of variables as
parameters, but may return, at most, only one
variable of one type
23
Using the Customer Class with Functions
24
A Program That Calls Two Ex3-11.cpp
}
25
Passing Addresses to
Functions
• Just as variable values may be passed to and
returned from functions, so may variable addresses
• Passing an address to a function avoids having the
function copy the passed object, a process that
takes time and memory
• You also can pass addresses to a function if you
want a function to change multiple values
• If you pass addresses to function, however, the
function can change the contents at those actual
memory addresses, eliminating the need to return
any values at all
26
Passing Addresses to
Functions
• As an alternative to the program shown in Figure 4-27,
you can pass two memory addresses to one function,
making a single function call, as shown in Figure 4-28
• In the program shown in Figure 4-28, four items are
passed to the results() function: the value of a, the value
of b, the address of dividend, and the address of
modulus
• In turn the results() function receives four items:
– num1, which holds the value of a
– num2, which holds the value of b
– oneAddress, a pointer that holds the address of dividend
– anotherAddress, a pointer that holds the address of modulus
27
A Program That Calls One
Function to Get Two Results Ex3-12.cpp
28
Passing Addresses to
Functions
• Passing an address of a variable to a
function has a number of advantages:
– If the function is intended to alter the variable, it
alters the actual variable, not a copy of it
– You can write the function to alter multiple values
– When you send the address of a variable to a
function, the function does not need to make a
copy of the variable
29
Using Reference Variables
with Functions
30
Declaring Reference Variables
31
Declaring Reference Variables
Ex3-13.cpp
Ex3-14.cpp
32
Declaring Reference Variables
33
Passing Variable Addresses to
Reference Variables
• Reference variables are easier to use because you
don’t need any extra punctuation to output their
values
34
Comparing Pointers and
References in a Function Header
35
Passing Variable Addresses to
Reference Variables
• When you pass a variable’s address to a function,
whether with a pointer or with a reference, any
changes to the variable made by the function also
alter the actual variable
• In addition, the function no longer needs to make a
copy of the variable
• A function that receives an address may change
the variable—but sometimes you might not want
the variable changed
36
Using a Constant Reference
37
Passing Arrays to Functions
38
Ex3-15.cpp
Passing an Array to a Function
39
Inline Functions
40
Using an Inline Function
41
Inline Functions
43
Using Default Arguments
44
Using Default Arguments
45
Examples of Legal and Illegal
Use of Functions with Default
Parameters Ex3-16.cpp
46
Overloading Functions
47
Overloading Functions
48
Three Overloaded Functions Ex3-17.cpp
Ex3-18.cpp
That Perform Similar Tasks
49
A Simple Recursion Function
#include <iostream.h>
int Fac(int n)
{
if (n > 1)
return Fac(n-1) * n;
else
return 1;
}
void main()
{ int i;
cout<<"Enter a number: ";
cin >>i;
cout<<"The factorial of "<<i<<" is "<<Fac(i)<<endl;
}
50
Summary
51
Summary
52
Summary
53
Summary
• An inline function is a small function with no
overhead
• You should use inline functions when the number of
statements is small and when the function is called
infrequently
• Default parameters provide values for any parameters
that are missing in the function call
• C++ allows you to reuse, or overload, function names
• To prevent ambiguity, overloaded functions must
have argument lists of different types
54