Functions
pass-by-value and pass-by-reference
Computer Programming
What is function?
2
! A collection of statements that perform a specific task.
! Functions are used to break a problem down into
manageable pieces
! Write several small functions to solve a specific part of the
problem
! A function can be invoked multiple times. No need to
repeat the same code in multiple parts of the program.
Function in C++
3
! The C++ standard library provides a rich collection of
functions for
! Mathematical calculations (#include
! String manipulations (#include
! Input/output (#include
How to use function written by others?
4
#include
#include
using namespace std;
void main()
{
double area,side;
cout << "Enter the area of a square:"; cin >> area;
side=sqrt(area);
cout << "The square has perimeter: " << 4*side;
}
Tell compiler that you are
going to use functions
defined in cmath package
Pass area to the function sqrt which
will return the square root of area
Function invocation
5
! During program execution, when a function name followed by
parentheses is encountered, the function is invoked and the
program control is passed to that function; when the function
ends, program control is returned to the statement immediately
after the function call in the original function
Write your own function
(User defined functions)
6
! Define a function printHello which accepts an
integer n as input
! The function should print "Hello" n times, where n
is an integer
Function Components
7
void printHello (int n){
int i;
for (i=0; i
return d;
}
calMax float f1
float f2
float float calMax (float f1,float f2){
if (f1>f2)
return f1;
else
return f2;
}
The return value can be user input, result of processing / calculation …etc
Parameters Passing: Pass-by-Value
14
• When a function is invoked, the arguments within the
parentheses by default are passed using pass-by-value
• As only the value is passed, the parameter can be:
• Constant: e.g. myFunc(10);
• Expression: e.g. myFunc(1+2*3*y);
• Variable: e.g. myFunc(num);
• Consider the 3rd case above (i.e. argument is a variable)
Since only the value is passed, so even if you try to change the
function’s local variable, the original is not affected!
• In other word, when you call myFunc(num), the function can
not change the value of the num enclosed inside parenthesis.
(unless you use the non-default, pass-by-reference mechanism in p32)
Parameters Passing: Pass-by-Value
15
void f (int x){
x=4; //we modify the value x to 4…
//but do we modify y (of main) at the same time? NO
y=4; //syntax error: y is local to main
}
void main(){
int y=3;
f(y);
cout << y; //print 3, y remains unchanged
}
The variable x and y are local variables.
x is local to f(), so we cannot use x in main().
y is local to main (), so we cannot use y in f().
x and y are two independent variables. When x is modified, y will not be
affected.
What if we rename x to y in f()?
(also possible, it’s not syntax error!)
16
void f (int y){
y=4; //modify y in f(), not the one in main()
}
void main(){
int y=3;
f(y);
cout << y; //print 3, y remains unchanged
}
In this program, there are two (unrelated) variables, both called y.
One is defined in f() and another one is defined in main().
In f(), y in f() is modified.
However, y in main() is not affected.
Then how to let f()modify y?
17
int f (int x){
x=4; //we modify the value x to 4
//Do we modify y at the same time? NO
return x;
}
void main(){
int y=3;
y=f(y);
cout << y; //print 4
}
If pass-by-value is used, the only way is to assign the
return value of f( ) to y
After the function call, y gets a value of 4
Return value
18
int y=32
y=100
We assign the return value of f(y) to the variable y.
What is y? Ans: 100
Function f(y)
return y;
100y=f(y)
The return statement
19
! When a return is encountered, the value of the (optional) expression
after the keyword return is sent back to the calling function
! Also, all statements after return are skipped
(i.e. exit the function immediately)
! Syntax:
return expression;
return;
Example:
return (a+b*2);
! Note: you can only write return (without the following expression) if the
function is of type void
Example: findMax
20
Suppose we need to write a function findMax, which return the
larger value among the two input integers.
E.g.
When x>y, the expression findMax(x, y) should evaluate to
a value of x
cout << findMax(4, 3); //print 4 (first parameter)
When y>x, the expression findMax(x, y) should evaluate to
a value of y
cout << findMax(3, 4); // print 4 (second parameter)
Function definition
21
int findMax (int n1, int n2) {
if (n1 > n2)
return n1;
else
return n2;
}
The return type of the variable is int
There are two arguments: n1 and n2, separated by a comma.
IMPORATNT: The type of EACH variable should be specified individually.
Error: int findMax (int a, b);
IMPORATNT: When using branching like if/switch, let’s make sure
that all paths give a return value!
int findMax (int n1, int n2) {
if (n1 > n2) return n1;
return n2;
}
Also ok to write: (without else) why?
Calling findMax()
22
int max;
int x=3;
int y=4;
max=findMax(x, y);
The value of this expression is 4. Assign 4 to max
The variable max will hold the value of x when x>y.
Otherwise, max will hold the value of y.
Flow of control
23
int findMax (int n1, int n2) {
if (n1>n2)
return n1;
else
return n2;
}
void main(){
int max;
int x=3;
int y=4;
max=findMax(x, y);
}
When findMax() is called,
the value of x(3) is copied to the variable n1
the value of y(4) is copied to the variable n2
Finding the max of 3 numbers, i, j, k
24
int i,j,k;
int max;
cin >> i >> j >> k;
//find the max of i, j, k
___ = findMax(___, ___);
___ = findMax(___, ___);
cout << "max is " << max; Answer 25 int i,j,k; int max; cin >> i >> j >>k;
//find the max of i, j, k
max = findMax(i, j);
max = findMax(max, k);
cout <<"max is " << max;
Alternatively, just chain them up and write as:
cout<<"max is " << findMax(i, findMax(j,k) );
What is the output of the following program?
26
void f(int y, int x){
cout << "x=" << x << endl;
cout << "y=" << y << endl;
}
void main(){
int x=3, y=4;
f(x, y);
}
Variables in function are unrelated to the variables in main
Answer
27
x=4;
y=3;
The x, y in main() is UNRELATED to the
local x, y in f().
It is just “by-luck” that they have the
same names…
Exercise
28
Rewrite the radius.cpp (on next page) by defining two
additional functions.
areaOfCircle :
Given a radius r, return the area of a circle
PrintResult :
Given a radius r and area a, generate the output
Original radius.cpp
29
#include
#include
using namespace std;
const double PI=3.141592653589793;
void main()
{
int radius;
float area;
cout << "Radius:";
cin >> radius;
area = PI * radius * radius;
cout << fixed << setprecision(2);
cout << "Area = " << PI << "*" << radius <<"*" << radius;
cout << "=" << area << endl;
}
Radius:5
Area = 3.14 * 5 * 5 = 78.54
Sample input/output
Answer
30
#include
#include
using namespace std;
const double PI=3.141592653589793;
//define the function areaOfCircle
//define the function printResult
void main(){
int radius;
float area;
cout << "Radius:"; cin >> radius;
}
Answer
31
#include
#include
using namespace std;
const double PI=3.141592653589793;
float areaOfCircle(int r){ /*r=radius*/
float result;
result= PI * r* r;
return result;
}
void printResult(int r, float a){ /*r=radius; a=area*/
cout << "Area = " << PI << "*" << r << "*" << r << "=" << a <
area=areaOfCircle(radius);
printResult(radius, area);
}
Parameters Passing: Pass-by-Reference
32
• Parameters pass to a function can be updated inside the function
• In function definition: Add ‘&’ in font of the parameter(s)
• When calling the function: As usual… ‘&’ is not needed, but..
• Argument must be variable, it cannot be constant / expression
void swap(int &a, int &b){
int temp;
temp=a;
a=b;
b=temp;
}
void main(){
int x=1,y=3;
cout << "x:"<
! A recurrence relation: (induction)
n! = n*(n-1)! for n>0
! E.g.:
3! = 3 * 2!
= 3 * 2 * 1!
= 3 * 2 * 1 * 0!
= 3 * 2 * 1 * 1
39
Iterative vs. Recursive
40
int factorial(int n)
{
int i, fact = 1;
for (i = 1; i <= n; i++) { fact = i * fact; } return fact; } int factorial(int n) { if (n==0) return 1; return n*factorial(n-1); } Iterative Recursive Summary 41 ! Functions simplifies the logic by breaking down the big problem into smaller parts ! Syntax: return_type Function_name(paramaters) {…} ! The keyword return is used to: ! Quit a function, and ! Report the answer to the caller ! Function prototype/body must declared before it can be used. ! Parameters by default uses pass-by-value, therefore updating the variable in function do not affect the original. ! A function may optionally uses pass-by-reference (&), which directly uses the original variable.