Professional Documents
Culture Documents
DITG1113-Lecture 7 - Function Part 2
DITG1113-Lecture 7 - Function Part 2
Function
(Part 2)
BY: MARLIZA BINTI RAMLY
LECTURE 7
1
Learning Outcomes
At the end of this lecture, you should be able to:
explain parameter passing in programs using: Pass by
Value and Pass by Reference.
use reference variables as parameters.
LECTURE 5 2
Passing Variables to a Function
3
LECTURE 5 3
Sending Data into a Function
• Values are passed to a function during the function call:
e.g.: pow(a, b)-> passes values of a and b
to function pow.
• Values passed to function are arguments. An argument can also be called an actual
parameter.
• Variables in a function header that hold the values passed as arguments are
parameters. A parameter can also be called a formal parameter.
LECTURE 5 4
Passing Multiple Arguments
LECTURE 5 5
Passing Variables By Value
6
LECTURE 5 6
Pass By Value Concept
=7;
=5; arguments
7
Pass By Value : Programming Example
//prototype declaration
#include <iostream> Output :
void fun (int x); 5
int main ( )
5
{
int a = 5;
a 5
cout << a << endl;
fun(a);
cout << a << endl;
One-way Pass by value
return 0;
communication
} // main (x is a duplicate of a)
LECTURE 5 8
Passing Variables By Reference
9
LECTURE 5 9
Using Reference Variables as Parameters
LECTURE 5 10
Passing by Reference
LECTURE 5 11
Pass By Reference Concept
=7;
=5;
Purpose of Function
Reference variables
exchange :
7 To exchange the values of
two numbers
12
LECTU
Pass By Reference : Programming Example
//prototype declaration
#include <iostream> Output :
void fun (int& x);
5
int main ( )
{
8
int a = 5;
cout << a << endl;
fun(a);
cout << a << endl;
return 0; a
} // main
5 8 Pass by Reference
void fun (int& x) (x is an alias for a)
{ x
x = x + 3;
return;
} // fun
LECTURE 5 13
Reference Variable : TAKE NOTE
LECTURE 5 14
Parameter passing : TAKE NOTE
(pass by value vs. pass by reference)
Pass by value
15
a copy of data is created and placed in a local variable in the called function
ensure that regardless of how the data is manipulated and changed in the called
function, the original data in the calling function are safe and unchanged
Pass by reference
sends the address of a variable to the called function
use the address operator (&) in the parameter of the called function
anytime we refer to the parameter, therefore we actually referring to the original
variable
if the data is manipulated and changed in the called function, the original data in the
calling function is changed
-END-
LECTURE 5 15