4 Functions
4 Functions
COMPUTER
PROGRAMMING
C++ Functions
Modules
2
Functions can be
Programmer-defined.
Built-in: pow, sqrt, .. etc.
Advantage
make programs easier to write, test, debug and maintain.
4
5
Functions Syntax
6
1 2 3
ReturnType FctName(Parameter List) Function Header
{
action1;
action2; 1
..
Function Body
actionN; 2
return value ;
}
Function Name and Return
7
Type
Function name follows rules of naming identifiers as variables and
constants.
Function return ONLY one value.
Function return types:
Built-in data types.
User-defined data types.
Nothing is returned by using keyword void.
} } }
Function Parameters
8
Provide the communication links between the main program and its
functions.
return value ;
DataType parameterName
}
Problem
9
Write a program that asks the user for the exam grade and prints a
message indicating if the user has passed the exam or not.
#include <iostream>
using namespace std;
int main()
{
int grade;
return 0;
}
Naming functions:
Read_Grade
Display_Msg main Fct
main
Read_Grade Display_Msg
Display_Msg
Analyzing Flow of Control-2
een
s cr n
on Mai
age l t o
ess ontro
1
ym c
p l a t urn
Dis D re
Start here
AN
end
4
D s de
AN a
g e d_ G r
ssa a
me by Re
l ay
i s p rn e d
t o d re t u
ok e de
I n v e gra
main Fct
th
er
us
e
th
m
f ro
d
ea r
er ut
us inp
m e
return 0 ;
f ro th
ut n
ur
i np t
3
ad Re
re
to
Read_Grade
ke
vo
In
2
6
11
Read_Grade
Main Fct
Main Fct
Read_Grade(){
void
int
}
12
Defining Functions (cont.)-3
13
Main Fct
Read_Grade Display_Msg
#include <iostream>
using namespace std;
int main()
{ Read_Grade
int grade;
int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade; grade scope
return grade;
}
void Display_Msg(int g)
{
if (g>60) cout<<"You passed"; g scope
else cout<<“You failed";
}
Using Functions-4
15
#include <iostream>
using namespace std;
// ====== You Must Define your Modules before Main ======
int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade;
return grade;
}
void Display_Msg(int g)
{
if (g>60) cout<<"You passed";
else cout<<“You failed";
}
// ====================== Main Fct ======================
int main()
{
// Invoke read module and store returned input
// Invoke display module and pass the grade
return 0;
}
Using Functions (cont.)-4
16
int n = Read_Grade();
if ( Read_Grade() == 3 ) …… … …
#include <iostream>
using namespace std;
// ====== You Must Define your Modules before Main ======
int Read_Grade()
{
int grade;
//grade is a local variable
cout<<"Enter your grade:\n";
cin>>grade;
return grade;
}
void Display_Msg(int g)
{
if (g>60) cout<<"You passed";
else cout<<“You failed";
}
// ====================== Main Fct ======================
int main()
{
int n = Read_Grade(); // Invoke read function
Display_Msg(n); // Invoke display function
return 0;
}
Using Library Functions
20
Examples
Header File Function call Example Value
<cmath> pow(x,y) pow(2,3) 8
<iomanip> setprecision(n) setprecision(2)<< 1.2345 1.23
Function Prototype
21
Usually placed at the top of the program to tell the compiler that the
function exists.
return x * x;
}
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
} Error: function undeclared before use
'square': identifier not found
int square( int x )
{
return x * x;
}
Solution -1
24
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
}
Solution -2
25
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
int a = 10;
cout << a << " squared: " << square( a ) << endl;
return 0;
}
Identifiers
Variable or object.
Function.
Scope of Identifier
Portion of the program where an identifier can be used.
Identifier is “known” and can be used in all functions from the point at
Examples
Examples
Block scope ends at the terminating right brace (}) of the block in which
cout << "local x in main's outer scope is " << x << endl;
cout << "local x in main's inner scope is " << x << endl;
} // end new scope
cout << "local x in main's outer scope is " << x << endl;
return 0;
}
Function / Inner Block Scope (can be used only
inside the inner block defined in Main)
31
Function Signature
32
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
int main()
{
return 0;
} // end main
Compilation Error -2
34
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
class Num {
int main() {
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
#include <iostream>
using namespace std;
int main()
{
cout << square( 7 ); // calls int version
cout << endl;
cout << square( 7.5 ); // calls double version
cout << endl;
return 0;
}
42
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << multi( 7,5 ); // calls 2
parameter version
cout << endl;
cout << multi( 7 ); // calls 1 parameter
version
cout << endl;
return 0;
}
43
#include <iostream>
using std::cout;
using std::endl;
{
return x * y;
}
int main()
{
cout << multi( 7,5.5 ); // calls
int,double version
cout << endl;
cout << multi( 7.5,3 ); // calls
double,int version
cout << endl;
return 0;
}
44
Reference Variables
45
grab
memory for
a
// create an integer
an integer
int a ; and labels it
as "a"
int& b = a ;
//OR
"b" is just
Int &b = a ;
another label
b
for the same
b is a "reference".
memory
int& means "make a label to reference an integer"
Example count
int count = 1; 1
count
int &cRef = count; 1 cRef
count
cRef++; cRef
2
#include <iostream> Example #1
using std::cout;
using std::endl;
x=3
int main()
{ y=3
int x = 3; x=7
int &y = x; // y refers to (is an alias for) x
y=7
cout << "x = " << x << endl << "y = " << y << endl;
y = 7; // actually modifies x
cout << "x = " << x << endl << "y = " << y << endl;
return 0; // indicates successful termination
} // end main
int main()
{
int x = 3;
int &y; // Error: y must be initialized
cout << "x = " << x << endl << "y = " << y << endl;
y = 7;
cout << "x = " << x << endl << "y = " << y << endl;
return 0;
}
47
Passing Arguments
48
Pass-by-reference
Gives called function the ability to access and modify the caller’s
argument data directly
Reference Parameter
49
& placed after the parameter type in the function prototype and
function header
Example
#include <iostream>
using std::cout;
using std::endl;
int main() x
{
int x = 2; 2
// demonstrate squareByValue
cout << "x = " << x << " before squareByValue\n";
cout << "Value returned by squareByValue: "
<< squareByValue( x ) << endl;
cout << "x = " << x << " after squareByValue\n" << endl;
return 0;
} number
int squareByValue( int number )
{ 2
return number *= number; // caller's argument not modified
}
Pass By Reference
51
#include <iostream>
using std::cout;
using std::endl;
int main()
z
{
int z = 4; 4 numberRef
// demonstrate squareByReference
cout << "z = " << z << " before squareByReference" << endl;
squareByReference( z );
cout << "z = " << z << " after squareByReference" << endl;
return 0;
}
void squareByReference( int &numberRef ) {
numberRef *=
numberRef; // caller's argument modified }
Common Errors
52
Compilation errors
Declaring function has parameters of the same type as char a,b instead of
char a, char b.
Invoking function before it is defined, e.g. when f1 invokes f2, f2 must be
defined before f1.
Attempting to use a function that has no return value in an expression.