Chapter 3 Functions
Chapter 3 Functions
Fundamentals of Programming II
Chapter Three
Functions
1
October 2013
Agenda
What is a function?
Sharing data among
Types of C++ functions: functions through
User-defined function parameters
functions Value parameters
Standard functions Reference
C++ function structure parameters
Function signature Const reference
Function body
parameters
Declaring and
Scope of variables
implementing C++ Local Variables 2
functions Global variable
Introduction to Functions
Complex problem is often easier to solve by
dividing it into several smaller parts (Modules),
each of which can be solved by itself.
This technique called “Divide and Conquer”
In C++ Modules known as Functions & Classes
main() then uses these functions to solve the
original problem.
Programs use “new” and “prepackaged” modules
New: programmer-defined functions & classes
Prepackaged: from the standard library 3
Introduction to Functions
Bad Development Approach Wise Development Approach
main() main()
{ {
-----
----- •Easer To
----
----- Design }
----- Build function f1()
Debug {
.
Extend ---
. Modify ---
. Understand }
----- Reuse function f2()
----- Better Organization {
--- 4
Return 0; ---
} }
C++ Standard Functions
C++ language is shipped with a lot of functions which
are known as standard functions
These functions are groups in different libraries which
can be included in the C++ program, e.g.
Math functions are declared in <math.h> library
Character-manipulation functions are declared in
<ctype.h> library
C++ is shipped with more than 100 standard
libraries, some of them are very popular such as
<iostream.h> and <stdlib.h>, others are very
specific to certain hardware platform, e.g. 5
<limits.h> and <largeInt.h>
Standard (Predefined)
Functions
• Predefined functions Make sure to use the
• Part of the C++ language required #include file
• Provided in function libraries
• Examples:
abs(x), sin(x), log(x), pow( x,
n)
• These functions will return a value
• To be printed cout << sin (x);
• To be assigned y = pow (3, 4.5);
• To be used in an expression 3.14 * sqr(r)
6
Predefined Functions
7
Function Input & Output
8
Information to function
can come from
param eters or an input
stream
Parameters
Return
value
Information from
function can come
through a return 9
value or an output
stream
Advantages of Functions
Easier to understand
Divide and conquer
Manageable program development
Software reusability
Use existing functions as building blocks for new
programs
Abstraction- hide internal details (library
functions)
Avoid code repetition – inheritance
10
Called several times in the same program
Advantages of Using Functions
11
Advantages of Using Functions
4. While working on one function, you can focus
on just that part of the program
• construct it,
• debug it,
• perfect it.
5. Different people can work on different functions
simultaneously.
6. If a function is needed in more than one place in
a program, or in different programs, you can
write it once and use it many times 12
Examples
#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions
void main()
{
char ch; Explicit casting
cout << "Enter a character: ";
cin >> ch;
cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
if (isdigit(ch))
cout << "'" << ch <<"' is a digit!\n";
else
cout << "'" << ch <<"' is NOT a digit!\n";
}
13
User Defined Functions
Although C++ is shipped with a lot of standard
functions, these functions are not enough for
all users, therefore, C++ provides its users with
a way to define their own functions (or user-
defined function)
For example, the <math.h> library does not
include a standard function that allows users to
round a real number to the ith digits, therefore,
we must declare and implement this function
ourselves 14
Syntactic Structure
A C++ function consists of two parts
The function header, and
The function body
The function header has the following
syntax
<return value> <name> (<parameter list>)
The function body is simply a C++ code
enclosed between {} 15
Examples of User-Defined
16
Examples of User-Defined
Function
header
Function body
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
17
Why Function Signature Needed?
For Information Hiding
If you want to create your own library and share it
with your customers without letting them know the
implementation details, you should declare all the
function signatures in a header (.h) file and
distribute the binary code of implementation file
For Function Abstraction
By only sharing function signatures, we have the
liberty to change the implementation details from
time to time to
- improve function performance
18
- make the customers focus on the purpose of the
function, not its implementation
Function Signature
The function signature is actually similar to
the function header except in two aspects:
- The parameters’ names may not be
specified in the function signature
- The function signature must be ended by a
semicolon
Example Unnamed
Parameter
Semicolon
;
double computeTax(double) ; 19
Function Definitions
can be placed anywhere in the program after
the function prototypes.
If a function definition is placed in front of
main(), there is no need to include its
function prototype.
Function definition format
return-value-type function-name(parameter-list)
{
declarations and statements
20
}
Function-name: any valid identifier
Function Definitions
Return-value-type: data type of the result
(default int)
void- indicates nothing returned
Parameter-list:
- comma separated list of arguments
- Data type needed for each argument
explicitly
- If no arguments use void or leave blank
21
Function Definitions
Declarations & statements: function body
(block)
- Variables can be declared inside blocks
- Functions can not be defined inside other
functions
Returning control
If nothing returned
return;
or, until reaches right brace
22
If something returned
return expression;
Function Definitions
Example function
int square( int y )
{
return y * y;
}
return keyword
o Returns data, and control goes to function’s caller
If no data to return, use return;
o Function ends when reaches right brace
Control goes caller
23
o Functions cannot be defined inside other functions
Function Prototypes
It declares the input (parameters) & output (return)
parameters of the function, includes
Function name
Parameters – what the function takes in
Return type – data type function returns (default int)
It only needed if function comes after in program
Must match function definition
Function prototype
int maximum(int, int, int);
Definition
int maximum(int x, int y, int z);
{ 24
….
}
Function Prototype
• Recall that the compiler must know certain things about your
function
• When it finds a function call in your source code
• Must know information in heading
• Your program must have at least the heading of a function
before it is invoked
• Usually listed before function main ( )
• View example
25
Alternative to Prototype
• Also possible to place whole function definition before main
()
• This is a requirement in some languages (Pascal)
• Either is acceptable in this class
• There may be a standard required of programmers within a
particular organization
• View Example
26
Flow of Control
• First statement executed in any program is the first statement
in the function main( )
• When another function called
• logical control passed to first statement in that function’s body
• program proceeds through sequence of statements within the
function
• When last statement of function executed
• control returns to where function was called
• control given to next command after the call
27
Flow of Control
void main ( )
{ . . .
print_summary (rpt_total);
revenue = rpt_total * .72675;
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
} - first statement of main
- function call, jumps to first statement
of that function
- proceeds through function
- returns to next statement after call
28
Function of three parameters
#include <iostream.h>
// function definition
int thefunctionname(int parameter1, double parameter2){
// Now the function can use the two parameters
// parameter1 = argument 1, parameter2 = argument2
32
Passing Arguments to Function
Function Arguments can be come in 3 flavors:
- Value parameters - which copy the values
of the function arguments
- Reference parameters - which refer to the
function arguments by other local names
and have the ability to change the values of
the referenced arguments
- Constant reference parameters – similar to
the reference parameters but can not change
the values of the referenced arguments 33
Passing by Values
This is what we use to declare in the function
header, e.g.,
int max (int x, int y);
- x and y are value parameters
- Calling max function as max (4, 7), values 4
and 7 are copied to x and y respectively
- Calling as max(a,b), where a=40 and b=10,
values 40 &10 are copied to x and y
Once the value parameters accepted copies of
34
the corresponding arguments data, they act as
local variable!
Example
#include <iostream.h>
int x; // Global variable
void increment (int x) {
x = x + 1;
cout<< “x in increment ”
<<x<<endl; Output
}
int main() { q in increment 4
int q = 3; q in main 3
increment (q); //does nothing
cout<<“q in main ”<< q <<endl; 35
}
Reference Parameters
If we want to change the values of the original
function arguments or return with more than
one value from the function
Defined by adding & in front of the parameter
name, e.g.,
36
Exercise #1
int main() {
int Number1 = PromptAndRead();
int Number2 = PromptAndRead();
if (Number1 > Number2) {
Swap(Number1, Number2);
}
cout << "The numbers in sorted order: “ << Number1
<< ", " << Number2 << endl;
return 0;
}
void Swap(int &a, int &b) {
int Temp = a;
a = b;
b = Temp;
return; 37
}
Consider
int I = 5;
void Swap(int &a, int &b)
int j = 6; {
Swap (i, j); int Temp = a;
int a = 7; a = b;
int b = 8; b = Temp;
Swap (b, a); return;
}
38
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void main ()
{
int x = 4; // local variable
fun(x);
cout<<x<<endl; void main()
{
} 1 int x = 4; 4 x
fun(x); 39
cout << x << endl;
}
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void fun( int & y )
void main () {
{ 3 cout<<y<<endl;
int x = 4; // local variabley=y+5;
}
fun(x);
cout<<x<<endl; void main()
{
} int x = 4; 4 x
2 fun(x); 40
cout << x << endl;
}
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void fun( int & y )
void main () {
{ cout<<y<<endl;
4 y=y+5;
int x = 4; // local variable 9
}
fun(x);
cout<<x<<endl; void main()
{
} int x = 4; 4 x
2 fun(x); 41
cout << x << endl;
}
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void fun( int & y )
void main () {
{ cout<<y<<endl;
int x = 4; // local variabley=y+5;
5 }
fun(x);
cout<<x<<endl; void main()
{
} int x = 4; 9 x
2 fun(x); 42
cout << x << endl;
}
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void main ()
{
int x = 4; // local variable
fun(x);
cout<<x<<endl; void main()
{
} int x = 4; 9 x
fun(x); 43
6 cout << x << endl;
}
Exercise #2
#include <iostream.h>
void fun(int &y)
{
cout << y<<endl;
y = y + 5;
}
void main ()
{
int x = 4; // local variable
fun(x);
cout<<x<<endl; void main()
{
} int x = 4; 9 x
fun(x); 44
cout << x << endl;
7 }
Scope Rules
45
Scope of an Identifier
• The scope of an identifier refers to where in the program an
identifier is accessible
• Local identifier - identifiers declared within a function (or
block)
• Global identifier – identifiers declared outside of every
function definition
• C++ does not allow nested functions
• The definition of one function cannot be included in the body of
another function
46
47
Global Variables
• Some compilers initialize global variables to default values
• The operator :: is called the scope resolution operator
• By using the scope resolution operator
• A global variable declared before the definition of a function
(block) can be accessed by the function (or block) even if the
function (or block) has an identifier with the same name as the
variable
48
Global Variables (continued)
• C++ provides a way to access a global variable declared after
the definition of a function
• In this case, the function must not contain any identifier with
the same name as the global variable
49
Side Effects of Global Variables
• Using global variables has side effects
• Is not independent
50
Side Effects of Global Variables
(continued)
• If more than one function uses the same global variable and
something goes wrong
51
Static and Automatic Variables
• Automatic variable - memory is allocated at block entry and
deallocated at block exit
• Static variable - memory remains allocated as long as the
program executes
• Variables declared outside of any block are static variables
• By default, variables declared within a block are automatic
variables
• Declare a static variable within a block by using the reserved
word static
52
Static and Automatic Variables
(continued)
• The syntax for declaring a static variable is:
static dataType identifier;
• The statement
static int x;
declares x to be a static variable of the type int
• Static variables declared within a block are local to the block
• Their scope is the same as any other local identifier of that
block
53
Function Overloading
• In a C++ program, several functions can have the same name
• This is called function overloading or overloading a function
name
54
Function Overloading
(continued)
• Two functions are said to have different formal parameter
lists if both functions have:
• A different number of formal parameters, or
• If the number of formal parameters is the same, then the data
type of the formal parameters, in the order you list them, must
differ in at least one position
55
The functions functionSix and functionSeven both
have three formal parameters and the data type of the
corresponding parameters is the same; therefore, these
functions have the same formal parameter list 56
Function Overloading
(continued)
• Function overloading: creating several functions
with the same name
• The signature of a function consists of the function
name and its formal parameter list
• Two functions have different signatures if they have
either different names or different formal parameter
lists
• Note that the signature of a function does not
include the return type of the function 57
These function headings correctly overload the function
functionXYZ:
• Both of these function headings have the same name and same
formal parameter list
• Therefore, these function headings to overload the function
functionABC are incorrect
• In this case, the compiler will generate a syntax error
58
• Note that the return types of these function headings are
different
Functions with Default
Parameters
• When a function is called
• The number of actual and formal parameters must be the same
59
Functions with Default
Parameters (continued)
• If you do not specify the value of a default parameter
• The default value is used
• All of the default parameters must be the rightmost
parameters of the function
• In a function call where the function has more than one
default parameter and a value to a default parameter is not
specified
• You must omit all of the arguments to its right
60
Functions with Default
Parameters (continued)
• Default values can be constants, global variables, or function
calls
• The caller has the option of specifying a value other than the
default for any default parameter
61
62
63
Constant Arguments
64
Constant Reference
Parameters
• Constant reference parameters are used under the following two
conditions:
• The passed data are so big and you want to save time and computer
memory
• The passed data will not be changed or updated in the function body
• For example
void report (const string & prompt);
• The only valid arguments accepted by reference parameters and
constant reference parameters are variable names
• It is a syntax error to pass constant values or expressions to the (const)
reference parameters
65
Example
double computeTaxes(double income)
#include <iostream>
{
#include <string>
if (income<5000) return 0.0;
using namespace std;
return 0.07*(income-5000.0);
}
// Function Signature
double getIncome(string);
double getIncome(string prompt)
double computeTaxes(double);
{
void printTaxes(double);
cout << prompt;
double income;
void main()
cin >> income;
{
return income;
// Get the income;
}
double income = getIncome("Please enter the
employee income: ");
void printTaxes(double taxes)
// Compute Taxes {
double taxes = computeTaxes(income); cout << "The taxes is $" << taxes << endl;
}
// Print employee taxes
printTaxes(taxes);
}
66
Building Your Libraries
• It is a good practice to build libraries to be used by you and
your customers
• In order to build C++ libraries, you should be familiar with
• How to create header files to store function signatures
• How to create implementation files to store function
implementations
• How to include the header file to your program to use your user-
defined functions
67
C++ Header Files
• The C++ header files must have .h extension and should have
the following structure
• #ifndef compiler directive
• #define compiler directive
• May include some other header files
• All functions signatures with some comments about their
purposes, their inputs, and outputs
• #endif compiler directive
68
TaxesRules Header file
#ifndef _TAXES_RULES_ double computeTaxes(double);
#define _TAXES_RULES_ // purpose -- to compute the taxes
for a given income
#include <iostream> // input -- a double value
#include <string> representing the income
using namespace std; // output -- a double value
representing the taxes
double getIncome(string); void printTaxes(double);
// purpose -- to get the employee // purpose -- to display taxes to the
income user
// input -- a string prompt to be // input -- a double value
displayed to the user representing the taxes
// output -- a double value // output -- None
representing the income
#endif
69
TaxesRules Implementation
File
#include "TaxesRules.h"
double computeTaxes(double
income) void printTaxes(double taxes)
{ {
if (income<5000) return 0.0; cout << "The taxes is $" << taxes
return 0.07*(income-5000.0); << endl;
} }
70
Main Program File
#include "TaxesRules.h"
void main()
{
// Get the income;
double income =
getIncome("Please enter the employee income: ");
// Compute Taxes
double taxes = computeTaxes(income);
72
Inline Functions
Sometimes, we use the keyword inline to
define user-defined functions
- Inline functions are very small functions,
generally, one or two lines of code
- They are very fast functions compared to the
functions declared without inline keyword
Example
inline double degrees(double radian)
{
return radian * 180.0/3.1415; 73
}
Example
Write a function to compute the distance
between two points (x1, y1) and (x2, y2)
74
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0;
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2();
cout<<x<<endl;
}
75
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0; x 0
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2();
cout<<x<<endl; void main()
{
} 1 x+=4;
x++; 76
cout << x << endl;
}
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0; x 4
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2(); void main()
cout<<x<<endl; {
} x+=4;
2 x++; 77
cout << x << endl;
}
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0; x 5
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2();
cout<<x<<endl; void main()
{
} x+=4;
x++; 78
3 cout << x << endl;
}
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0; x 5
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2();
cout<<x<<endl; void main()
{
} x+=4;
x++; 79
cout << x << endl;
4 }
What Happens When we Use Inline
Keywords?
#include<iostream.h>
int x=0;
inline void f1(){x++;}
inline void f2(){x+=4;f1();}
void main ()
{
f2();
cout<<x<<endl;
}
80
Recursion
Recursion is the ability of a function to call
itself.
Consider the mathematical function n!
n! = n * (n-1) … * 2 * 1
is not mathematically precise because we use
an ellipsis (…) .
Consider the following formula definition
n! = 0, if n = 0
- n! = n * (n - 1)! if n > 0
81
- The factorial function is defined in terms of
itself
Example #1
#include<iostream.h>
#include<string.h>
int main ()
{
cout<< "Enter a positive integer: ";
int n;
cin>> n;
cout<< n <<"!=“<<factorial(n)<<endl;
return 0;
} 82
Example #1
int factorial(int n){
if (n == 0){
return 1;
}
else{
return n * factorial (n - 1);
}
}
C++ function mirrors the mathematical factorial definition
• If the value of n is 0, the value 1 is returned.
83
• Otherwise, the product of n and factorial(n - 1)
is returned.
Recursion Visualization
Consider cout<< n <<"!=“<<factorial(n)<<endl;
Activation records
n = 3 Factorial(3) = 3 * Factorial(2) = 3 * 2 = 6
n = 2 Factorial(2) = 2 * Factorial(1) = 2 * 1 = 2
n = 1 Factorial(1) = 1 * Factorial(0) = 1 * 1 = 1
n = 0 Factorial(0) = 1
Example #2: Fibonacci Series
Fibonacci series: 0,1,1,2,3,5,8,13…
• Each number is the sum of the previous two
• Can be solved recursively:
• fib(n) = fib (n-1)+fib(n-2)
long fibonacci(long n){
if (n == 0 || n == 1)//base case
return n;
else
return fibonacci (n - 1) +
85
fibonacci (n - 2);
}
Example #2: Fibonacci Series
Set of recursive calls to function fibonacci
f( 3 )
return f( 2 ) + f( 1 )
return f( 1 ) + f( 0 ) return 1
86
return 1 return 0
Recursion Vs Iteration
Repetition
- Iteration: explicit loop
- Recursion: repeated function calls
Termination
- Iteration: loop condition fails
- Recursion: base case recognition
Both can have infinite loops
Balance
- Choice between performance (iteration) and 87
good software engineering (recursion)
Function Overloading
Is a function that is defined more than once
with different data types or different number of
parameters
inline int max(int x, int y)
{
if(x>y) return x; else return y;
}
inline double max(double x, double y)
{
if(x>y) return x; else return y; 88
}
Sharing Data Among
User-Defined Functions
• There are two ways to share data among
different functions
• Using global variables (very bad practice!)
• Passing data through function parameters
• Value parameters
• Reference parameters
• Constant reference parameters
89
C++ Variables
• A variable is a place in memory that has
• A name or identifier (e.g. income, taxes, etc.)
• A data type (e.g. int, double, char, etc.)
• A size (number of bytes)
• A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using it
• Local variables – only the function that declare local variables see
and use these variables
• A life time (the duration of its existence)
• Global variables can live as long as the program is executed
• Local variables are lived only when the functions that define these
variables are executed
90
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
91
I. Using Global Variables
#include <iostream.h> x 0
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
92
I. Using Global Variables
#include <iostream.h> x 0
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl; void main()
{
} 1 f2();
cout << x << endl ;
}
93
I. Using Global Variables
#include <iostream.h> x 0
4
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main() void f2()
{
{ 2 x += 4;
f1();
f2(); }
cout << x << endl; void main()
{
} 1 f2();
cout << x << endl ;
}
94
I. Using Global Variables
#include <iostream.h> x 5
4
int x = 0; void f1()
{
void f1() { x++; } 4 x++;
void f2() { x+=4; f1(); } }
100
What is Bad About Using
Global Vairables?
• Not safe!
• If two or more programmers are working together in a program,
one of them may change the value stored in the global variable
without telling the others who may depend in their calculation on
the old stored value!
• Against The Principle of Information Hiding!
• Exposing the global variables to all functions is against the
principle of information hiding since this gives all functions the
freedom to change the values stored in the global variables at any
time (unsafe!)
101
Local Variables
• Local variables are declared inside the function body and exist
as long as the function is running and destroyed when the
function exit
• You have to initialize the local variable before using it
• If a function defines a local variable and there was a global
variable with the same name, the function uses its local
variable instead of using the global variable
102
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
103
Example of Defining and Using
Global and Local Variables
#include <iostream.h> x 0
int x; // Global variable
Void fun(); // function signature Global variables are automatically
initialized to 0
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
104
Example of Defining and Using
Global and Local Variables
#include <iostream.h> x 0
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void main()
void fun()
{
x = 4; x 10
fun();
{
cout << x << endl;
int x = 10;
}
4 cout << x << endl;
}
void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} 2 fun(); 108
void main()
void fun()
{
x = 4; x 10
fun();
{
cout << x << endl;
int x = 10;
}
cout << x << endl;
5 }
void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} 2 fun(); 109
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} fun(); 110
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{ void main()
int x = 10; // Local variable {
cout << x << endl; x = 4;
} fun(); 111
115
Thank You !!!
Any Questions
??
116