Вы находитесь на странице: 1из 34

Functions

Call by value & call by refrence


2 Monday, March 30, 2020

Function Declarations vs. Definitions,


cont.
 The compiler refers to the function prototype to check
that calls to function contain
 the correct numbers and types of arguments
 and that the types of the arguments are in the correct order.
 Each argument must be consistent with the type of the
corresponding parameter.
 If the arguments passed to a function do not match the
types specified in the function’s prototype, the compiler
attempts to convert the arguments to those types.
3 Monday, March 30, 2020

Example 2, cont.
How might we call our function from a main() function?

#include <iostream>
long factorial(int); // declaration
Void main()
{
int x;
cout << “Please enter a number> “ << endl;
cin >> x;
cout << x << “! is “ << factorial(x) << endl;
}

 When a function is declared separately from its definition, this is called a


forward declaration.
 Forward declarations need only to specify return type, parameters type,

parameter number and order of parameters. Parameter names are irrelevant.


4 Monday, March 30, 2020

Example 2, cont.
The definition contains the actual code for the function.

long factorial(int n) // declarator


{
long result = 1, k = n;// function body.
while(k > 1)
{
result *= k--;
}
return result;
}

 The definition consists of a line called the declarator,


followed by the function body.
5 Monday, March 30, 2020

Function with no return results


 If the function does return a result, the statement
return expression;

 Ifthe function does not return a result (i.e., it has a


void return type), control returns when the
program reaches the function-ending right brace,
or by execution of the statement
return;
6 Monday, March 30, 2020

Functions with no return results. The use of void


// void function example
#include <iostream>
using namespace std;

void printmessage (int x)


{ for (int i=0; i<=x; i++)
cout << "I'm a function!“<< x ; }

void main ()
{ printmessage (5); }
Function Definitions with Multiple Parameters
 A function is a group of statements that is executed when it is called
from some point of the program.

 Function format with multiple parameters :


ReturnType funcName ( parameter1, parameter2, ...)
{ statements }
 Multiple parameters are specified in both the function prototype and the
function header as a comma-separated list.

 Function with no parameters is specified by writing either void or


nothing at all in parentheses.
ReturnType funcName ( ) or ReturnType funcName (void)

Monday, March 30, 20 7


20
8 Monday, March 30, 2020
  Function Definitions with Multiple Parameters,
cont.
ReturnType funcName (parameters)
{ code to perform a task }

---- ;
Var = funcName (arguments); //function call
---;

• There must be one argument in the function call for each


parameter in the function definition.
• Arguments is the name of the values that the function
call passes to the function for the parameters.
Monday, March 30, 20 9
20
Example

#include <iostream>
using namespace std;

int addition (int a, int b)


{
int r;
r=a+b;
return r;
}
Monday, March 30, 20 10
20
Example , cont.
int main ()
{
int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The output of program:
The result is 8

Monday, March 30, 20 11


20
Example (some different calling methods), cont.
int main ()
{
int x=5, y=3, z;
z = addition (5,3);
cout << "The result is " << z << '\n';
cout << "The second result is " << addition (5,3) << '\n';
cout << "The third result is " << addition (x,y) << '\n';
z= 4 + addition (x,y);
cout << "The fourth result is " << z << '\n';
return 0;}

The result is 8
The second result is 8
The third result is 8
The fourth result is 12
Monday, March 30, 20 12
20
Reference Parameters “Argument Passing”
 There are two ways to pass arguments to functions in C++:
 Pass by VALUE
 Pass by REFERENCE
 Pass by VALUE
 The value of a variable is passed along to the function
 The function creates copies of the argument passed to it.
 If the function modifies that value, the modifications stay within the
scope of that function and do not affect the original variable’s value in
memory.
 Pass by REFERENCE
 A reference to the variable is passed along to the function.
 The called function access the caller’s data directly.
 If the function modifies that value, the modifications appear also
within the scope of the calling function, i.e. The function can change
the original variable’s value in memory.
Monday, March 30, 20 13
20
Argument Passing by Value
 Passing Constants

int z;
z = addition (5,3);

 Passing Variables
int x=5, y=3, z;
z= addition (x,y);

Monday, March 30, 20 14


20
Problem: i- What is the output of the following program?
void cubev(int );

void main( )
{ Call by Value
int n=5;
cout<< n<<endl;
cubev( n);
cout<< n<<endl;
}

void cubev(int x){


x= x * x * x ;
}
Monday, March 30, 20 15
20
Pass by VALUE
Start of the call Main() cubev

n 5
5 x

At the end of call


Main() cubev

n 5
125 x

Monday, March 30, 20 16


20
Problem: i- What is the output of the following program?
void cubev(int );

void main( )
{ Call by Value
int n=5;
cout<< n<<endl; 5
cubev( n); 5
cout<< n<<endl;
}

void cubev(int x){ Prob: ii - Modify this program to


x= x * x * x ; give the cube using Call by
} Reference?
Monday, March 30, 20 17
20
Solution: Cuber function using Call by Reference

void cuber(int &);

void main( ){ 5
int n=5; 125
cout<< n<<endl;
cuber(n );
cout<< n<<endl;
}

void cuber(int &x){


x= x * x * x ;
}
Monday, March 30, 20 18
20
Pass by reference
Start of the call Main()
cuber

n 5 x

At the end of callMain()


cuber

n 125 x

Monday, March 30, 20 19


20
Why use Pass By Reference?
 Because you really want changes made to a parameter to
persist in the scope of the calling function.
1. You need to return more than one value to the calling
function.
2. Because you are passing a large amounts of data
 Passing by reference passes merely a reference

(pointer) to the data, not the data itself.

Monday, March 30, 20 20


20
Why use Pass By Reference?
1- Because you want to return two values
void order (int & a, int & b)
{
if(a > b)
{ int temp = a; //swap them
a = b;
b = temp;
}}
void main()
{
int num1 = 21, num2 = 12; //this pair not ordered
order (num1, num2);
cout << “num1 = “ << num1 << endl;
cout << “num2 = “ << num2 << endl; }
Monday, March 30, 20 21
20
Pass by reference
Main() order
num1 21 a

num2 12 b

Main()
order
num1 12 a

num2 21 b

Monday, March 30, 20 22


20
23 Monday, March 30, 2020

Pass by Reference
(with and without the const keyword)
24 Monday, March 30, 2020

const Function Arguments


 Suppose you want to pass an argument by reference for
efficiency, but not only do you want the function not to
modify it, you want a guarantee that the function cannot
modify it.

 To obtain such a guarantee, you can apply the const modifier


to the variable in the function declaration.
25 Monday, March 30, 2020

Example
void aFunc(int& a, const int& b); //declaration
void main()
{
int alpha = 7;
int beta = 11;
aFunc(alpha, beta); }
//--------------------------------------------------------------
void aFunc(int& a, const int& b) //definition
{
a = 107; //OK
b = 111; //error: can’t modify constant argument
}
Example
//Program to demonstrate call-by-reference parameters.
#include <iostream>
using namespace std;
void get_numbers(int& input1, int& input2); //Reads two integers.
void swap_values(int& variable1, int& variable2);
//Interchanges the values of variables
void show_results(int output1, int output2);
//Shows the values of variables in order.

int main( )
{ int first_num, second_num;
get_numbers(first_num, second_num);
swap_values(first_num, second_num);
show_results(first_num, second_num);
return 0; }
Example cont….
void get_numbers(int& input1, int& input2)
{ cout << "Enter two integers: ";
cin >> input1 >> input2; }

void swap_values(int& variable1, int& variable2) {


int temp;
temp = variable1;
variable1 = variable2;
variable2 = temp; }

void show_results(int output1, int output2)


{ cout << "In reverse order the numbers are: "<< output1 << " " <<
output2 << endl; }
Call-by-Reference in Detail
void get_numbers(int& input1, int& input2);
 Now consider a function call like the following from the same display:

get_numbers(first_num, second_num);
 When the function call is executed, the function is not given the
argument names first_num and second_num.
 Instead, it is given a list of the memory locations associated with each
name. (ex. 1010, 1012)
 It is these memory locations that are associated with the formal
parameters.
 The first memory location is associated with the first formal
parameter, the second memory location is associated with the second
formal parameter, and so forth.
Behavior of Call-by-Reference
Arguments
 void get_numbers(int& <the variable at memory location
1010>, int& <the variable at memory location 1012>)
{ cout << "Enter two integers: ";
cin >> <the variable at memory location 1010>
>> <the variable at memory location 1012>; }
The swap_values Function
swap_values(first_num, second_num);
 the definition of the function swap_values uses
a local variable called temp. This local variable
is needed.
 You might be tempted to think the function
definition could be simplified to the following:
The swap_values Function
 The variables first_num and second_num are
substituted for the formal parameters variable1
and variable2 so that, with this incorrect
function definition, the function call is
equivalent to the following:
 first_num = second_num;
 second_num = first_num;
Tips
 Call-by-reference parameters are not restricted to
void functions.
 It is perfectly legitimate to mix call-by-value and call-
by-reference formal parameters in the same function.
 For example,

void GCF(int& par1, int par2, double& par3);


Test Your Self
 What is the output of the following program?
#include <iostream>
void figure_me_out(int& x, int y, int& z);
int main( )
{
using namespace std;
int a, b, c;
a = 10;
b = 20;
c = 30;
figure_me_out(a, b, c);
cout << a << " " << b << " " << c;
return 0;
}
void figure_me_out(int& x, int y, int& z)
{
using namespace std;
cout << x << " " << y << " " << z << endl;
x = 1;
y = 2;
z = 3;
cout << x << " " << y << " " << z << endl;
}

Вам также может понравиться