Functions

Functions
CSIS1117 Computer Programming
c1117 lecture 5
1
Contents








What is a function?
Predefined function provided by C++ library
M h i
Mechanism
for
f function
f
ti calls
ll
User defined function
function prototype
Local variables
Scope of variables
Gl b l variables
Global
i bl
c1117 lecture 5
2
Function



A function is a small program which accomplishes
a specific task.
We can “interact”
interact (give input and get output) with
functions in our programs for finishing some tasks
C
C++
libraries
lib i provide
id a lot
l t off predefined
d fi d functions
f
ti
that we can use.

For example,
F
l sqrt(x) is
i a function
f
i in
i the
h cmath
h library
lib
to compute the square root of x (x is a real number).
c1117 lecture 5
3
Passing input to
the function sqrt
int main(){
...
...
sqrt(x);
...
}
Our program
x
x
double sqrt(…){
...
}
In cmath library
Getting
g output
p from
the function sqrt
We don’t need to write codes for finding the square root
of a number (actually it is difficult to do so), we can call
the function sqrt to help.
c1117 lecture 5
4

We can call (or invoke) a function using its name
with necessary input (arguments)


At most one value is returned by a function as the
output (return value).


The type of the arguments are specified for each
function
The type of the return value is specified for each
function
The function call,
call sqrt(x) is an expression

We can place a function call in any places where an
expression is expected.
expected
c1117 lecture 5
5
Function

We usually use the following notation to describe a
function: double sqrt(double x)
Data type for
the return value

Data type for
the argument
In calling a function, we need to consider:




The name of the function
Type of the return value
Number of arguments
Type of each argument
c1117 lecture 5
sqrt
double
1
double
// function call
double val = sqrt(9.0)
6


The program that invoke the function is the caller
and the called function is the callee.
We need to specify the library,
library which contains the
code of the predefined functions, in our program.


e g #include <cmath> for using sqrt()
e.g.
Example: Try to find the area of a triangle given 3
sides
id a, b and
d c.

The two roots can be calculated by the following
f
formula:
l
s = (a+b+c)/2
( b )/2
area= {s(s-a)(s-b)(s-c)}
c1117 lecture 5
7
Example
#include <iostream>We need to include the libraryy in
using the predefined function
#include <cmath>
using
g namespace
p
std;
;
int main() {
Invoke the
double a,b,c,s,area;
sqrt function
cin
i >> a >> b >> c;
in cmath
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
area
sqrt(s (s a) (s b) (s c));
cout << "the area is : " << area;
return 0;
}
c1117 lecture 5
We can put the function calls in any places where
expressions are expected.
8
Flow of control



The execution of the statements in the main
function is from top to bottom.
The flow of control is passed from one statement
to the other.
In evaluating an expression involving function call,
the flow of control actually has been suspended in
that statement.



The control is passed to the function (sub-program)
When the sub-program finishes, the control is passed
back to the original statement
The control is resumed from that statement.
c1117 lecture 5
9
Mechanism for function calls
#include <cmath>
int main() {
double a,b,c,s,area;
, , , ,
;
cin >> a >> b >> c;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
t( *( )*( b)*( ))
cout << "the area is : " << area;
return 0;
Main memory
3
a
4
b
c
5
6
s
area
}
3
4
5
c1117 lecture 5
Command
prompt
10
Mechanism for function calls
#include <cmath>
int main() {
double a,b,c,s,area;
, , , ,
;
cin >> a >> b >> c;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
t( *( )*( b)*( ))
cout << "the area is : " << area;
return 0;
}
Program is suspended,
suspended the
control and the
data(parameters) are passed to
the
h sub-program
b
off the
h
function
c1117
lecture 5
Main memory
3
a
4
b
c
5
6
s
area
double sqrt(double x){
...}
in cmath library
11
Mechanism for function calls
#include <cmath>
int main() {
double a,b,c,s,area;
, , , ,
;
cin >> a >> b >> c;
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
t( *( )*( b)*( ))
cout << "the area is : " << area;
return 0;
}
Once sub
sub-program
program finishes,
finishes
the control and the return
value are p
passed back to
the original statement
c1117 lecture 5
Main memory
3
a
4
b
c
5
6
s
6
area
double sqrt(double x){
...}
in cmath library
12
Some predefined functions
In library cmath -- #include<cmath>
Function
Description
double sqrt(double x)
square root of x
double pow(double x, double y) x to the power of y (ie. xy)
double abs(double x)
absolute value of x
double ceil(double x)
ceiling, e.g. ceil(3.2)=4
double floor(double x)
floor, e.g. floor(3.2)=3
In library cstdlib -- #include<cstdlib>
int rand()
c1117 lecture 5
return a random integer
13
Type casting

Sometimes, we need to convert from one type to
Sometimes
another:
int tol_candy,
tol candy no_of_people;
no of people;
cin >> tol_candy >> no_of_people;
cout << "The number of candies p
per p
person: "
<< tol_candy / no_of_people;
After evaluating the expression, force the type of
the value to the type some_type.
You don’t need to include any library for using static_cast.

See casting.cc as an example
c1117 lecture 5
14
// since i and j are both integer variables, i/j is
an integer division
division.
// After casting one of the operand, the division
become dobule division.
cout << "Double division of the two integers: " <<
endl;
cout << "static_cast<double>(i)/j = ";
cout << static_cast
_
<double> (i) / j << endl;
cout << "Or using the simply vsrsion: " << endl;
cout << "i / (double) j = ";
cout << i / (double) j << endl;
return 0;
}
c1117 lecture 5
15
Expressions for arguments

Functions require zero, one, or more arguments.


e.g. rand takes no arguments, sqrt takes one and pow
takes two.
An argument can also be an expression. The
expression is evaluated before calling the function.
double w, h;
w*w + h*h is evaluated
before calling sqrt
cin >> w >> h;
cout << sqrt(w*w + h*h) << endl;

As function call is also an expression, it can be used
in the argument of another function
double root1 =(-b
=( b + sqrt(pow(b
sqrt(pow(b,2)-4*a*c))/(2*a);
2) 4*a*c))/(2*a);
c1117 lecture 5
16
User defined functions



The programs you
you’ve
ve written so far consists of
only the main function. In fact, you can define
other functions to help organizing your program
Designing functions in programs is the most
important skill in programming.
programming
Advantages of using functions:


Re-usability: Once we implemented a function, we can
invoke it many times in different parts of a program.
R d bilit The
Readability:
Th program becomes
b
more structural.
t t l
c1117 lecture 5
17
Problem

Consider a p
problem: Given 3 coordinates ((x1, y1),
(x2, y2) and (x3, y3), find the shortest distance
among
g the 3 pairs
p
of coordinates.



One solution is to calculate the distances of 3 pairs of
coordinates and return the shortest one.
In doing so, we have to write the codes for finding the
distance between a pair of coordinates three times,
even though they are very similar.
Moreover, it’s easy to make mistake if code is
d li t d
duplicated.
c1117 lecture 5
18
Problem
//finding the distance between (x1,y1)&(x2,y2)
double dx12, dy12, dist12;
dx12 = x1 – x2; dy12 = y1 – y2;
dist12 = sqrt(dx12 * dx12 + dy12 * dy12);
//finding the distance between (x1,y1)&(x3,y3)
double dx13, dy13, dist13;
dx13 = x1 – x3; dy13 = y1 – y3;
dist13 = sqrt(dx13 * dx13 + dy13 * dy13);
//finding the distance between (x2,y2)&(x3,y3)
...
Codes are repeated and it’s easy to make mistakes.
c1117 lecture 5
19
Defining functions

The natural solution to avoid code duplication is to
define a function.


We can define a function to find the distance of any two
coordinates.
Imagine that if there were such a predefined function
that takes a pair of coordinates and returns the distance
between them, our code could be simplified as:
//finding the
//coordinates
double dist12
double dist23
double dist31
c1117 lecture 5
distances of the 3 pairs of
= pair_distance(x1, y1, x2, y2);
= pair_distance(x2, y2, x3, y3);
= pair
pair_distance(x3,
distance(x3 y3,
y3 x1,
x1 y1);
20


Our next task is to design the function
pair_distance.
A function can be considered as a program with
input & output.



The arguments passed to the function is the input
The value/result computed by the function is the output
S closest.cc
See
l
t
as an example
l
c1117 lecture 5
21
Structure of a function
return type
function
name
parameters of the function
double
d
bl pair_distance(double
i di t
(d bl x1,
1 d
double
bl y1,
1
double x2, double y2){
Body of
double dx = x1 - x2;
the
double dy = y2 - y2;
function
double distance = sqrt(dx * dx + dy * dy);
return distance;
}
Variables can be declared
inside the function.
return statement: return
th value
the
l to
t caller
ll
c1117 lecture 5
22

A function heading consists of a return type
type, a
function name and a parameters list.



return type: specifying the type of value that the
function will send back to the caller, e.g. double.
function name: name of the function, e.g.
pair_distance
Parameter list: inputs
p
to the function. The parameter
p
types and number of parameters should be specified.
e.g. pair_distance takes 4 parameters which are
used
d to
t store
t
th
the arguments
t passed
d to
t it
it.

Each parameter has a type to denote the possible value
that can be stored
stored.
c1117 lecture 5
23



A function is defined uniquely by its heading
(function prototype).
We can put any no.
no of statements and declare
variables inside the function body.
Th value
The
l as wellll as the
th flow
fl
off control,
t l are sentt
back to the caller in the return statement

The execution of the function is terminated after the
return statement.
c1117 lecture 5
24
Understanding function calls


In reading a program with function definitions,
definitions we
shall not assume the execution starts from the top
till the bottom of the program file.
file
In fact, the execution begins at the main function,
no matter how many function definitions are put
before it.


See closest-fun.cc
closest fun cc
Therefore, to understand the computation of a
C
C++
program, we need
d to
t trace
t
th execution
the
ti iin
main.
c1117 lecture 5
25
Mechanism for function calls
…
double p
pair_distance(double x1, double
y1, double x2, double y2)
{ … }
i t main()
int
i () {
…
pair_distance(
_
… );
double dist12 = p
}
Execution starts at the main function
c1117 lecture 5
26
Mechanism for function calls
double pair_distance(double
x1 double y1
x1,double
y1, double x2
x2, double y2){
double dx = x1-x2;
double dy
y = y
y1-y2;
y
double dist = sqrt(dx*dx + dy*dy);
…
return dist;
double pair_distance(double
pair distance(double
px
px, double
}
py, double qx, double qy)
{ … }
int main() {
…
double dist12 = pair_distance(
pair distance( … );
}
When executing to a function call, the control is
suspended and passed to the function code.
c1117 lecture 5
27
Mechanism for function calls
double pair_distance(double
x1 double y1
x1,double
y1, double x2
x2, double y2){
double dx = x1-x2;
double dy
y = y
y1-y2;
y
double dist = sqrt(dx*dx + dy*dy);
…
return dist;
//in
cmathpair_distance(double
library
double
pair
distance(double
px
px, double
}
py, double
qx, double
qy)
double
sqrt(double
x){
double
;
{ … } val;
…int main() {
…
return
val; }
double dist12 = pair_distance(
pair distance( … );
}
The control is suspended again and
passed to the predefined function, sqrt.
c1117 lecture 5
28
Mechanism for function calls
double pair_distance(double
x1 double y1
x1,double
y1, double x2
x2, double y2){
double dx = x1-x2;
double dy
y = y
y1-y2;
y
double dist = sqrt(dx*dx + dy*dy);
…
return dist;
//in
cmathpair_distance(double
library
double
pair
distance(double
px
px, double
}
py, double
qx, double
qy)
double
sqrt(double
x){
double
;
{ … } val;
…int main() {
…
return
val; }
double dist12 = pair_distance(
pair distance( … );
}
After the return statement of sqrt is executed, the
result is returned to the caller (pair
(pair_distance),
distance)
and the control is resumed.
c1117 lecture 5
29
Mechanism for function calls
double pair_distance(double
x1 double y1
x1,double
y1, double x2
x2, double y2){
double dx = x1-x2;
double dy
y = y
y1-y2;
y
…
double dist = sqrt(dx*dx + dy*dy);
return dist; px, double
double pair_distance(double
py, double qx,
} double qy)
{ … }
int main() {
…
double dist12 = pair_distance( … );
}
After the return statement of pair_distance is
executed, the result is again returned to the caller
(the main function), and the control is resumed.
c1117 lecture 5
30
Viewing execution

We can also picture the execution of a program
using a tree-like diagram.
main()
pair_distance
(4 0 1 3)
(4,0,1,3)
sqrt(18)
c1117 lecture 5
pair_distance
(1 3 3 5)
(1,3,3,5)
sqrt(8)
pair_distance
(3 5 4 0)
(3,5,4,0)
sqrt(26)
31
Function prototype


The order of the functions in a p
program
g
matters.
 The compiler performs the translation by reading the
program from top to bottom.
 Errors will be given by compiler if the function is not defined
before it is called.
C++ required that either the complete function definition or the
function prototype appears in the code before the function is
called.
 Function prototype: just like the function heading
heading, specifies
the name, return type and the parameter list of the function.
 Function declaration should be ended with a semi-colon.
 Function can be defined in another file. In that case, we need
to include the function prototype in the file that uses this
function.
c1117 lecture 5
32
Function prototype


In writing the prototype, only the types in the parameter
list and the number of parameters are important. The name
of each parameter is optional.
Using prototypes, the function definitions can be placed in
arbitrary order.
Ends with a semi-colon
double pair_distance(double
x1,double y1, double x2, double y2);
double pair_distance(double, double,
double, double);
c1117 lecture 5
33
Function prototype
#include <iostream>
Defining the function
before main().
double pair_distance(double x1,
double y1, double x2, double y2)
{ … }
int main()
{ … }
#i l d <i
#include
<iostream>
t
>
Declare
ec a e tthe
e
function first
by prototype.
Defining the function
after
f
main().
()
c1117 lecture 5
double pair_distance(double x1,
double y1, double x2, double y2);
int main()
{ … }
double pair_distance(double x1,
double y1, double x2, double y2)
{ … }
34
Dummy names


The names of the parameters are dummy.
dummy They
can always be renamed without affecting the
meaning of the function.
function
Yet, it’s better to give meaningful names to
parameters.
parameters
double pair_distance(double px,
double py, double qx, double qy)
{ … }
These two functions are
the same, but it is more
readable if meaningful
names are used.
double pair_distance(double x1,
double y1, double x2, double y2)
{ … }
c1117 lecture 5
35
Boolean functions

Functions can return more than just number
number. In
fact, it can return bool, char, string, etc.
bool
b
l i
isValidTriangle(
V lidT i
l ( i
int
t a, int
i t b,
b int
i t c){
){
if ((a+b > c) && (b+c > a) && (c+a > b))
return true;
else
return false;
}
// a simpler version
bool isValidTriangle( int a, int b, int c){
return (a+b > c) && (b+c > a) && (c+a > b);
}
c1117 lecture 5
36
Void function



In some situations
situations, we use functions just for
completing subtasks, without computing or
returning any data.
data
The return type of this kind of functions is void,
which means nothing.
nothing
For a void function, when the flow of control
reaches
h the
th end
d off th
the ffunction
ti b
body,
d th
the ffunction
ti
finishes and returns the control to the caller.

S temperature.cc
See
c1117 lecture 5
37
void print_temperature(double t) {
co t << “The temperature
cout
temperat re in Centigrade is:
is ”
”;
cout << t << endl;
if( t > 30){
cout << " It is very hot! " << endl;
// the codes after, will be skipped if this
//return is executed.
return;
cout << “ All statements after the return statement”;
cout << “ won‘t be executed!” << endl;
}
if( t < 5){
cout << " It is very cold! " << endl;
return;
}
cout << " It is so cool! " << endl;
}
c1117 lecture 5
38
Return statement



Note that when a return statement executes,
executes the
control is transferred to the caller immediately, i.e.
anything after that return statement will not be
carried out.
Because of the behavior of return
return, we can omit
some else part of an if-statement. See
digitword cc
digitword.cc.
Return statement can also be used in void
f
function.
ti
See temperature-fun.cc
t
t
f
c1117 lecture 5
39
string digit_to_word(
digit to word( int digit ){
// v. important comment
// precondition: 0 <= digit <= 9
// the p
programmer
g
has to make sure the p
precondition satisfies
// postcondition: 0 --> "zero", 1 --> "one", ..., 9 -> "nine"
if ( digit == 1 )
return "one"; //leave the sub-program at once and pass the
// control back to the caller
if ( digit == 2 )
return "two";
if ( digit == 3 )
return "three";
" h
"
……
c1117 lecture 5
40
Arguments Vs parameters



Parameters are listed in the function heading and
are used in the body of the function definition.
Arguments are listed in parentheses after the
function name in a function call, acting as the
input to the function
function.
C++ is a strong-typing language. The type of
arguments
t passed
d to
t a ffunction
ti mustt match
t h with
ith
the type of the parameters specified.

Type mismatch between parameters and arguments can
be caught by compiler.
c1117 lecture 5
41
Precondition & Postcondition

Precondition specifies
p
the criteria that the
parameters must satisfy.


The caller of the function has to make sure that the
precondition
diti is
i satisfied.
ti fi d
Postcondition shows the result when the function
finishes execution,
execution provided that the precondition is
satisfied.
// pre: three sides s1
s1, s2
s2, s3 of a valid triangle
// post: return the angle opposite to s1
double find_angle(double s1,double s2,double s3)
{ … }
// pre: n >= 0
// post: return y, s.t. y*y = n
d bl sqrt(double
double
(d bl n)
) { … }
c1117 lecture 5
42
Local variables

We can declare and use variables inside the function body.
 These variables are called local variables.
 They are “local”
local to the function only and cannot be used
outside the function.
 They
y can have the same name as the variable alreadyy
declared in the main function. They are different
variables.
 In fact, the variables declared in the main function, i.e.
in main(), are local variables of main, which cannot be
used in the user-defined
user defined functions.
functions
 Parameters of a function are the local variables of the
function
function.
c1117 lecture 5
43
Local variables
Function declaration
void print_output();
()
int main(){
x, y and sum are the
int x,
x y,
y sum;
l
local
l variables
i bl of the
cin >> x >> y;
main function. They can
onlyy be used inside the
sum = x + y;
main().
print_output();
}
void print_output(){
cout << “the sum of your input is: ”
<< sum << endl;
}
Compiler will give error message that the
variable is not declared.
c1117 lecture 5
44
void print_output(int
(
t);
)
int main(){
The parameter t is a
int x,
x y,
y sum;
local variable of the
cin >> x >> y;
function print_output.
sum = x + y;
print_output(sum);
}
void print_output(int t){
cout << “the sum of your input is: ”
<< t << endl;
}
c1117 lecture 5
45
Scope of a variable

Scope of a variable is the portion of the program
that the variable is well-defined and can be used.


The scope of a local variable starts from its
declaration up to the end of the block.
block




It is not allowed to refer to variables beyond its scope.
scope
A block is delimited by { and }.
V i bl declared
Variables
d l d in
i an outer
t bl
blockk can also
l be
b referred
f
d
to in the inner block.
We can declare variables with the same name as
long as they have different scopes.
S scope.cc as an example.
See
l
c1117 lecture 5
46
x, y and w are
the local
variables of the
function fn,
fn their
scopes are
within fn.
The scope of k is
only within the
inner block.
c1117 lecture 5
int fn(int x, int y){
int w;
y, w and k are the
if( x > y){
local variables of the
int k = w;
main
i function,
f
ti
same
...
variable names can be
}
used in different
...
}
scopes.
int main(){
int x
x,
If same variable x is
int y, w, k;
declared in the inner
...
block the scope of
block,
if(
if(...){
){
the first x is blocked
int x;
in the scope of the
...
}
second
d x.
}
47
Global variables

It usually happens that the same variables are
needed by more than one functions. In that case,
we need to declare these variables in each
function using them.


e.g.
e
g the constant value PI and the variable radius are
used in functions cal_area and cal_circumference
in circle.cc
In order to eliminate these redundancies, we use
global variables instead of local variables.

See circle-global.cc as an example.
c1117 lecture 5
48
Global variables


Global variables are declared outside any functions.
Global variables can be used in any function definitions
that follows the variable declaration.
double x;
int fn
fn_2(...);
2(
);
int fn_1(...)
{...}
int y;
int main()
{
{...}
}
int fn_2(...)
{...}
c1117 lecture 5
Variable x can
b used
be
d in
i fn_1,
f 1
fn_2 and the
main function.
Variable y can
only be used in
fn_2 and the
main function.
49
Top-Down
Top
Down Program Design



Start with the most abstract formulation of a
problem and work down to more detailed subproblems.
problems
A complex task is divided into simpler subtasks,
which are further divided until the task is
manageable.
E h subtask
Each
bt k is
i implemented
i l
t d by
b a sub-program
b
block – functions.
c1117 lecture 5
50
Tax Program


Calculate the salary tax:
Divide into subproblem:


Gett user iinformation,
G
f
ti
such
h as salary,
l
number
b off
childs, dependent parents, etc.
C
Compute
t th
the ttotal
t l ttax allowance
ll
off a user





Compute basic allowance
Compute child allowance
Compute parent allowance
Compute the net chargeable income
Compute the tax return
c1117 lecture 5
51
Example C++ code
Note: The following is not complete program, just
illustrate the idea of decomposing tasks. The functions
do not have complete parameters, and return value
specification.
int main()
{
Get_User_Information();
Compute_Total_Allowance();
Compute_Net_Chargeable_Income();
Compute Tax();
Compute_Tax();
return 0;
}
c1117 lecture 5
52
Compute_Total_Allowance()
{
Compute_Basic_Allowance();
Comp te Child Allo ance()
Compute_Child_Allowance();
Compute_Parent_Allowance();
Total Allowance=Basic
Total_Allowance
Basic_Allowance
Allowance +
Child_Allowance + Parent_Allowance;
return;
}
Further decomposition may be needed until we get a function
that can be easily implemented.
c1117 lecture 5
53