To lustrate, suppose we have a program that must input the radius of a circle from the user and compute evaluates returns 0.707, sin 45° =0.707; that is to say sin x the sine of the give
Trang 1Chapter 3
Functions
Introduction
Trang 2A function is a unit of code designed to perform a certain task In order to perform its task, a function
me information and/or returns some information The concept is somewhat similar to
e trigonometric function
typically inputs so
mathematical functions Consider th sin( )x , which takes a parameter x and
) some value, namely the sine of x For example, the sine of 45° is approximately
, given 45° as a parameter, the function works to compute
hen returns or evaluates to the result 0.707
he utility of functions can be be easily demonstrated if we first consider a program without them To lustrate, suppose we have a program that must input the radius of a circle from the user and compute
evaluates (returns
0.707, sin( )45° =0.707; that is to say sin( )x
the sine of the given angle, and t
T
il
the area throughout the program (Recall the area of a circle is given by A=π ⋅r2, where r is the radius
of the given circle.) As a first attempt we might do the following:
Program 3.1: Program without Functions
float area = PI*radius*radius;
cout << "Area = " << area << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Enter a radius of a circle: ";
cin >> radius;
area = PI*radius*radius;
cout << "Area = " << area << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Enter a radius of a circle: ";
Trang 3Press any key to continue
ate code which
to m to be made, it would be necessary to make the change
compute the area and return the result For the sake of discussion, let us assume such a unction exists and call it Area; moreover, assume the task of Area—that is inputting the radius from the user, computing the area and returning the result—is executed by simply writing “Area()” in a C++
program (When we execute a function we say that we call it or invoke it.) Program 3.1 can now be
rewritten like so:
Program 3.2: Revision of Program 3.1 using an Area function Note that this program will not compile yet because the function Area is not actually defined Note that we have bolded the calls to the area function
The main problem which Program 3.1 suffers is code duplication—there is duplic
nti lly performs the same task Besides bloating the code, prog
aintain because if changes or corrections need
orr ction in every duplicated instance In a large real world pr
e fi e and making changes is not only a waste of time, but it is prone to e
The problems of Program 3.1 could be resolved using a function whose sole task is to input the radius from the user,
// Input a radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// and so on
}
Program 3.2 is much cleaner and more compact There is no longer duplicate code for the input code
pute a and calculation code—we simply write “Area()” wherever necessary to input a radius and com
Trang 4circle area Moreover, if a change or correction needs to be made to the code Area executes, it would
modification of the Area function With that, let us see how Area works
ons, let us examine the actual syntactic details of making
unction (i.e., create) the following needs to be specified:
pe of value the function evaluates to)
name (i.e., what you want to refer to it as)
eter list (i.e., what values does it take as input, if any)
plem
only necessitate
3.1 User Defined Functions
Now that we understand the benefits of functi
and using them To define a f
return type (i.e., the ty
param
body (i.e., the code to be executed when the function is invoked)
3.1 shows the syntax of how the Area fun
Fi
im ented
Figure 3.1: Function definition
l compile and run
on of Program 3.2, this time with the Area function defined
lProgram 3.3 rewrites Program 3.2, this time defining Area so that the program wi
Program 3.3: Revisi
#include <iostream>
Trang 5// Input a radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// and so on
}
Observ
functio lared or defined before it is called, as the compiler must recognize the
nction before you call it A function declaration (also called a function prototype) consists of the
return type, function name, and parameter list followed by a semicolon—there is no body in a function
However, once call the function Program 3.4 rewrites Program 3.3 using a function declaration
e from Program 3.3 that the function Area is defined before any calls to that function A
n must be either dec
fu
declaration Once a function is declared, it can be defined elsewhere in the program
declared, the function definition can come even after you
Program 3.4: Revision of Program 3.3, this time using a function declaration
#include <iostream>
using namespace std;
// Function declaration The function declaration just tells the
// compiler the function exists (it will be defined later), and
// its name, return type and parameters
float Area();
int main()
Trang 6{
// Input a radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// Do some other work
cout << "Other work " << endl;
// Input another radius and output the circle area
cout << "Area = " << Area() << endl;
// and so on
}
// Function definition The function definition contains the
// fun ction body and consists of the code that specif ies what
// the function actually does
The Area function did not have a parameter But let us look at an example which does have a parameter
A useful function might be one that cubes (x ) the given input, as follows: 3
rogram 3.5: Function with a parameter We have bolded the function calls to
Paramete
Cube P
#include <iostream>
using namespace std;
// Declare a function called 'Cube' which has a parameter
// of type 'float' called 'x', and which returns a value
// of type 'float'
Trang 7float Cube( float x);
// Provide the definition of Cube it computes x^3
float Cube( float x)
Press any key to continue
The Cube function is similar to the function except that it takes a parameter (i.e., its parameter list side the parentheses of the function declaration/definition is not empty) A parameter is not a value in Area
riable) That is, the function caller will “pass in” or
le for the function to use The actual value passed into a
alled an argument
0) Here input0 is the argument—it stores a
Cube hat is, the value stored in input0 is copied into
meter x The word “copied” is important, as input0 and x are not the same variables but
the function is called This copying of argument value to rame he argument is copied to the parameter, the code inside the
e value that was passed into it
gure code relative to the calling program code Think of a
eed data into it (copy arguments into the parameters), it
s so n body), and it outputs a result (returns something back to u) Again, functions are useful primarily because they prevent code duplication and provide a level of
in
and of itself, but rather a value placeholder (va
“input” a value into this placeholder variab
particular function call is c
For example, in program 3.5, we write Cube(input
ecific value which is input into the function; t
sp
the Cube para
will contain copies of the same value when
ter is called passing by value Once t
pa
body of Cube can execute, where x contains th
Fi 3.2 shows how you can think of function
function as a separate “machine” where you f
mething with those parameters (functio
doe
yo
Trang 8code organization; that is, breaking up programs into more manageable parts, where each part does a specific task
Figure 3.2: Calling functions with parameters and returning results
3.1.3 Functions with Several Parameters
Functions are not limited to zero or one parameter, but can have several parameters The following program uses a function named PrintPoint, which takes three parameters: one each for the x-coordinate, y-coordinate and z-coordinate of a point The function then outputs the coordinate data in a convenient point format
Program 3.6: Functions with several parameters
Trang 9Press any key to continue
As Program 3.6 shows, additional parameters could be added and
is called, an argument for each parameter is provided separated with the comma operator
other thing to notice about the PrintPoint function is that because its sole task is to output a point the console window, it does not need to return a value It is said that the function returns void, and
specified for the return type Observe that you do not need to write a return
a function that returns void
nctions themselves can contain other code units such as if statements and loops Furthermore, these
s now to see how this vocabulary is used
code units can be nested This brings up the topic of variable scope Variable scope refers to what
variables a code unit can “see” or “know about” A variable defined inside a particular code unit is said
to be a local variable relative to that code unit Additionally, a variable defined outside a particular code unit is a global variable relative to that code unit (A subunit of code is not considered to be
“outside” the unit of code that contains the subunit.) A unit of code can “see” variables that are global and local, relative to it Let us look at a couple of example
Trang 10Press any key to continue
The first variable defined is gPI Because gPI is outside the code units of main and SphereVolume,
it is global relative to both of them, and both functions can “see”, use, and modify gPI
The next set of variables occurs inside the main function unit of code These variables, input0 and V,
re local to main and global to no code unit Therefore, main is the only code unit that can “see” them
ot “see” input0, and if you try to use input0 in SphereVolume,
error Note, however, that you can define a variable with the same variable
er code unit, as we do with V Because the variables V are defined in separate are completely independent of each other
ned, SphereVolume defines its own separate version of V This V is local to
lume is the only code unit that can “see” this V Additionally,
e When the argument input0 is passed into variable radius It is important to understand
t input0 and radius are separate variables in memory
t are destroyed when the program exits that code unit For example, when SphereVolume is invoked, the program will create memory for the variable V After
a
For example, SphereVolume cann
you will get a compiler
name as a variable in anoth
code units they
Finally, as already mentio
th m variable radius is local to SphereVolum
in input0 is copied to the
e para eter
the function, the value stored
es place and thathat this copy tak
Important: Variables declared in a code uni
the function ends (after V is returned) the memory for V is deleted
Trang 11rogram 3.8 also has a logic error Namely, the counting variable cnt is
er of loop cycles Recall the “important” note from the Section 3.2.1
id
neither local nor glo
“undeclare
Besides the compilation error, P
ot keeping track of the numb
n
Variables declared in a code unit are destroyed when the program exits that code unit Every time the for-loop repeats, cnt is re-created and re-destroyed after that loop cycle, and therefore, the value does not persist The program needs to be rewritten as follows:
Program 3.9: Revision of Program 3.8
Note that
re
Trang 12Press any key to continue
Recall that we can create varia
u
bles of t t in ifferent code units This is nctions b f op statements Program 3.10 eclares a variable called var local to main and assigns 5.0 to it The program then asks if var is greater
ut However, this presents a dilemma: Which
ar is used in the cout statement: the one local to the ‘if’ statement or the one local to main? As a
he same name if they exis dstraightforward with separate f ut can be tricky when using i /lo
Trang 133.3 Math Library Functions
s for many of the elementary math functions and operations,
oot and absolute value ust be included The
ble 3.
The C++ standard library provides function
such as trigonometric, logarithmic, and exponential functions, as well as square r
functions To use the standard math functions, the <cmath> header file m
following table summarizes some of the most commonly used math functions:
Ta 1: Some Standard Library Math Functions
( )x
ln
Remark 1: The trigonometric functions work in radians and not degrees A number x can be converted
from radians to degrees by multiplying it by 180° π For example:
x Likewise, a number x can be converted from degrees to radians
y multiplying it by π 180° For example: 360°=360°⋅π 180°=2π
b
Remark 2: The functions above work with floats, hence the ‘f’ suffixes The standard math library
t work with doubles The double versions are the same except that the ‘f’ example, the double version of the cosine function would be double x) In real-time 3D computer game graphics floats are typically used, which is the
e float versions were given in the above table
s how to call some of these “calculator” functions The results can be mputations on a calculator
also provides versions tha
ffix is omitted For
su
cos(double
son why th
rea
The following program show
verified by performing the co
P r 3.11: Examples of using the standard math
#include <iostream>
Trang 14cout << "cosf(0.0f) = " << cosf(0.0f) << endl;
cout << "sinf(quarterPI) = " << sinf(quarterPI) << endl;
cout << "sqrtf(2.0f) = " << sqrtf(2.0f) << endl;
cout << "logf(expf(1.0f)) = " << logf(expf(1.0f)) << endl;
cout << "powf(2.0f, 3.0f) = " << powf(2.0f, 3.0f) << endl;
cout << "fabsf(-5.0f) = " << fabsf(-5.0f) << endl;
cout << "floorf(2.3f) = " << floorf(2.3f) << endl;
cout << "ceilf(2.3f) = " << ceilf(2.3f) << endl;
Press any key to continue
3.4 Random Number Library Functions
The C++ standard library provides a function called rand (include <cstdlib>), which can be used to generate a pseudorandom number This function returns a random integer in the range [0,
Program 3.12: Random numbers without seeding