Unit 2
Unit 2
5
100
1
2
3
4
5
2
AGENDA
What is a function?
Types of C++ functions:
Standard functions Sharing data among functions through
User-defined functions
function parameters
Value parameters
C++ function structure Reference parameters
Function signature Const reference parameters
Function body
Scope of variables
Declaring and Implementing C++ Local Variables
functions Global variable
3
FUNCTIONS AND SUBPROGRAMS
The Top-down design appeoach is based on dividing the main problem into
smaller tasks which may be divided into simpler tasks, then implementing each
simple task by a subprogram or a function
A C++ function or a subprogram is simply a chunk of C++ code that has
A descriptive function name, e.g.
computeTaxes to compute the taxes for an employee
isPrime to check whether or not a number is a prime number
A returning value
The computeTaxes function may return with a double number representing the amount of taxes
The isPrime function may return with a Boolean value (true or false)
4
C++ STANDARD FUNCTIONS
C++ language is shipped with a lot of functions which are known
as standard functions
These standard 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. <limits.h> and <largeInt.h>
5
EXAMPLE OF USING
STANDARD C++ MATH FUNCTIONS
#include <iostream.h>
#include <math.h>
void main()
{
// Getting a double value
double x;
cout << "Please enter a real number: ";
cin >> x;
// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;
}
6
EXAMPLE OF USING
STANDARD C++ CHARACTER FUNCTIONS
#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions
void main()
{ Explicit casting
char ch;
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";
}
7
USER-DEFINED C++ 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
8
HOW TO DEFINE A C++ FUNCTION?
Generally speaking, we define a C++ function in two steps (preferably but not
mandatory)
Step #1 – declare the function signature in either a header file (.h file) or before the main function of
the program
Step #2 – Implement the function in either an implementation file (.cpp) or after the main function
9
WHAT IS THE SYNTACTIC STRUCTURE OF A C++ FUNCTION?
10
EXAMPLE OF USER-DEFINED
C++ FUNCTION
11
EXAMPLE OF USER-DEFINED
C++ FUNCTION
Function
header
12
EXAMPLE OF USER-DEFINED
C++ FUNCTION
Function
header
13
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
Unnamed Semicolon
Example
Parameter ;
double computeTaxes(double) ;
14
WHY DO WE NEED FUNCTION SIGNATURE?
15
EXAMPLE
#include <iostream>
double computeTaxes(double income)
{
#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: ");
}
// Print employee taxes
printTaxes(taxes);
} 16
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
17
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
18
TAXESRULES HEADER FILE
#ifndef _TAXES_RULES_ double computeTaxes(double);
#define _TAXES_RULES_ // purpose -- to compute the taxes for a given
income
// input -- a double value representing the income
#include <iostream>
// output -- a double value representing the taxes
#include <string>
using namespace std;
void printTaxes(double);
// purpose -- to display taxes to the user
double getIncome(string);
// input -- a double value representing the taxes
// purpose -- to get the employee income
// output -- None
// input -- a string prompt to be displayed to the
user
// output -- a double value representing the income #endif
19
TAXESRULES IMPLEMENTATION FILE
#include "TaxesRules.h"
return 0.07*(income-5000.0); cout << "The taxes is $" << taxes << endl;
} }
double income;
return income;
20
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);
21
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
Inline functions are very fast functions compared to the functions declared
without the inline keyword
Example
inline double degrees( double radian)
{
return radian * 180.0 / 3.1415;
}
22
EXAMPLE #1
Write a function to test if a number is an odd number
23
EXAMPLE #2
Write a function to compute the distance between two points (x1,
y1) and (x2, y2)
24
EXAMPLE #3
Write a function to compute n!
26
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
27
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
28
I. USING GLOBAL VARIABLES
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
29
I. USING GLOBAL VARIABLES
x 0
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
30
I. USING GLOBAL VARIABLES
x 0
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2(); void main()
{
cout << x << endl; 1 f2();
} cout << x << endl ;
}
31
I. USING GLOBAL VARIABLES
x 0
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2()
void f2() { x+=4; f1(); } {
void main() 2 x += 4;
f1();
{ }
f2(); void main()
{
cout << x << endl; 1 f2();
} cout << x << endl ;
}
32
I. USING GLOBAL VARIABLES
x 5
4
void f1()
#include <iostream.h>
{
int x = 0; 4 x++;
}
void f1() { x++; }
void f2()
void f2() { x+=4; f1(); } {
void main() x += 4;
3 f1();
{ }
f2(); void main()
{
cout << x << endl; 1 f2();
} cout << x << endl ;
}
33
I. USING GLOBAL VARIABLES
x 5
4
void f1()
#include <iostream.h>
{
int x = 0; x++;
5 }
void f1() { x++; }
void f2()
void f2() { x+=4; f1(); } {
void main() x += 4;
3 f1();
{ }
f2(); void main()
{
cout << x << endl; 1 f2();
} cout << x << endl;
}
34
I. USING GLOBAL VARIABLES
x 5
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2()
void f2() { x+=4; f1(); } {
void main() x += 4;
f1();
{ 6 }
f2(); void main()
{
cout << x << endl; 1 f2();
} cout << x << endl;
}
35
I. USING GLOBAL VARIABLES
x 5
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2(); void main()
{
cout << x << endl; f2();
7 cout << x << endl;
} }
36
I. USING GLOBAL VARIABLES
x 5
4
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2(); void main()
{
cout << x << endl; f2();
} cout << x << endl;
8 }
37
I. USING GLOBAL VARIABLES
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
38
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
39
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h> x 0
int x = 0;
Inline void f1() { x++; } The inline keyword
instructs the compiler
Inline void f2() { x+=4; f1();} to replace the function
call with the function
void main() body!
{
f2(); void main()
{
cout << x << endl; 1 x+=4;
} x++;
cout << x << endl;
}
40
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h> x 4
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2(); void main()
{
cout << x << endl; x+=4;
} 2 x++;
cout << x << endl;
}
41
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h> x 5
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2(); void main()
{
cout << x << endl; x+=4;
} x++;
3 cout << x << endl;
}
42
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h> x 5
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2(); void main()
{
cout << x << endl; x+=4;
} x++;
cout << x << endl;
4 }
43
WHAT HAPPENS WHEN WE USE INLINE KEYWORD?
#include <iostream.h>
int x = 0;
Inline void f1() { x++; }
Inline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
44
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!)
45
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
46
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;
}
47
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;
}
48
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 ????
fun(); {
cout << x << endl; 3 int x = 10;
} cout << x << endl;
}
void fun() void main()
{ {
int x = 10; // Local variable x = 4;
cout << x << endl; 2 fun();
} cout << x << endl;
} 50
EXAMPLE OF DEFINING AND USING GLOBAL AND LOCAL VARIABLES
#include <iostream.h>
x 4
int x; // Global variable
Void fun(); // function signature
void main()
void fun()
{
x = 4; x 10
fun(); {
cout << x << endl; 3 int x = 10;
} cout << x << endl;
}
void fun() void main()
{ {
int x = 10; // Local variable x = 4;
cout << x << endl; 2 fun();
} cout << x << endl;
} 51
EXAMPLE OF DEFINING AND USING GLOBAL AND LOCAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
void fun()
{ x 10
x = 4;
fun();
{
int x = 10;
cout << x << endl;
4 cout << x << endl;
}
}
void fun() void main()
{ {
int x = 10; // Local variable x = 4;
cout << x << endl; 2 fun();
} cout << x << endl;
} 52
EXAMPLE OF DEFINING AND USING GLOBAL AND LOCAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
void fun()
{
x 10
x = 4;
fun();
{
cout << x << endl;
int x = 10;
}
cout << x << endl;
5 }
void fun()
void main()
{
{
int x = 10; // Local variable
x = 4;
cout << x << endl; 2 fun();
}
cout << x << endl;
} 53
EXAMPLE OF DEFINING AND USING GLOBAL AND LOCAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void main()
{
x = 4;
fun();
cout << x << endl;
}
56
VALUE PARAMETERS
This is what we use to declare in the function signature or function
header, e.g.
int max (int x, int y);
Here, parameters x and y are value parameters
When you call the max function as max(4, 7), the values 4 and 7 are copied to
x and y respectively
When you call the max function as max (a, b), where a=40 and b=10, the
values 40 and 10 are copied to x and y respectively
When you call the max function as max( a+b, b/2), the values 50 and 5 are
copies to x and y respectively
57
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
#include <iostream.h> x 0
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4; void main()
{
fun(x/2+1);
1 x = 4;
cout << x << endl; fun(x/2+1);
} cout << x << endl;
} 58
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
#include <iostream.h> x 4
int x; // Global variable
void fun(int x)
{
cout << x << endl; void fun(int x )
x=x+5; {
} 3 cout << x << endl;
x=x+5;
void main()
}
{
x = 4; void main()
fun(x/2+1); {
x = 4; 3
cout << x << endl;
2 fun(x/2+1);
} cout << x << endl;
} 59
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
void fun(int x 8
3 )
cout << x << endl; {
x=x+5; cout << x << endl;
} 4 x=x+5;
}
void main()
{ void main()
x = 4; {
fun(x/2+1); x = 4;
2 fun(x/2+1);
cout << x << endl; cout << x << endl;
} } 60
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl; void fun(int x 3
8 )
{
x=x+5; cout << x << endl;
} x=x+5;
void main() 5 }
{
void main()
x = 4; {
fun(x/2+1); x = 4;
cout << x << endl; 2 fun(x/2+1);
cout << x << endl;
}
} 61
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
void main()
x = 4; {
fun(x/2+1); x = 4;
cout << x << endl; fun(x/2+1);
6 cout << x << endl;
}
} 62
EXAMPLE OF USING VALUE PARAMETERS AND GLOBAL VARIABLES
x 4
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
void main()
x = 4; {
fun(x/2+1); x = 4;
cout << x << endl; fun(x/2+1);
cout << x << endl;
}
7 } 63
REFERENCE PARAMETERS
As we saw in the last example, any changes in the value
parameters don’t affect the original function arguments
Sometimes, we want to change the values of the original function
arguments or return with more than one value from the function, in
this case we use reference parameters
A reference parameter is just another name to the original argument
variable
We define a reference parameter by adding the & in front of the
parameter name, e.g.
double update (double & x);
64
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
void main()
int x = 4; // Local variable {
fun(x); 1 int x = 4; ?
4 x
cout << x << endl; fun(x);
} cout << x << endl;
}
65
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{
cout << y << endl; void fun( int & y )
{
y=y+5; 3 cout<<y<<endl;
} y=y+5;
void main() }
{
void main()
int x = 4; // Local variable {
fun(x); int x = 4; ?
4 x
2 fun(x);
cout << x << endl; cout << x << endl;
} }
66
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{
void fun( int & y )
cout << y << endl; {
y=y+5; cout<<y<<endl;
} 4 y=y+5;
9
}
void main()
{ void main()
int x = 4; // Local variable {
int x = 4; ?
4 x
fun(x);
2 fun(x);
cout << x << endl; cout << x << endl;
} }
67
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{ void fun( int & y )
cout << y << endl; {
cout<<y<<endl;
y=y+5; y=y+5;
} 5 }
void main()
{ void main()
{
int x = 4; // Local variable int x = 4; ?
9 x
fun(x); 2 fun(x);
cout << x << endl;
cout << x << endl; }
} 68
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{ void main()
int x = 4; // Local variable {
int x = 4; ?
9 x
fun(x); fun(x);
cout << x << endl; 6 cout << x << endl;
}
}
69
EXAMPLE OF REFERENCE PARAMETERS
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{ void main()
{
int x = 4; // Local variable ?
9 x
int x = 4;
fun(x); fun(x);
cout << x << endl; cout << x << endl;
7 }
}
70
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
71
FUNCTION OVERLOADING
C++ enables several functions of the same name to be
defined, as long as they have different signatures.
linkage.
SIGNATURE OF A FUNCTION
A function’s argument list (i.e., number and type of argument) is known as
the function’s signature.
Functions with Same signature - Two functions with same
number and types of arguments in same order
variable names doesn’t matter. For instance, following two
functions have same signature.
void squar (int a, float b); //function 1
void squar (int x, float y);
75
Following code fragment overloads a function
name prnsqr( ).
76 76
void prnsqr (int i)
{
cout<<“Integer”<<i<<“’s square is”<<i*i<<“\n”;
}
void prnsqr (char c);
{
cout <<“No Square for characters”<<“\n”;
}
void prnsqr (float f)
{
cout<<“float”<<f <<“’s square is”<<f *f<<“\n”;
}
void prnsqr (double d)
{
cout <<“Double float”<<d<<“’s square is”<<d*d<<“\n’;
} 77 77
Resolution by Compiler when it sees second
function with same name
1) Signature of subsequent functions match previous function’s,
then the second is treated as a re-declaration of the first - Error
For example,
79 79
CALLING OVERLOADED FUNCTIONS
Overloaded functions are called just like other
functions. The number and type of arguments
determine which function should be invoked.
For instance consider the following code fragment:
prnsqr (‘z’);
prnsqr (13);
prnsqr (134.520000012);
prnsqr (12.5F);
80 80
STEPS INVOLVED IN FINDING THE BEST MATCH FOR A
FUNCTION CALL
A call to an overloaded function is resolved to a particular
instance of the function, there are three possible cases, a
function call may result in:
81 81
1. EXACT MATCH
For example, there are two functions with same name afunc:
void afunc(int);
void afunc(double);
afunc(0);
//exactly match. Matches afunc(int)
is matched to void afunc(int); and compiler invokes
corresponding function definition
83 83
For example, consider the following code fragment:
afunc (‘c’);
//match through the promotion;
matches afunc (int)
Will invoke afunc(int)
84 84
Compiler resolves
square (‘a’) to
square(int)
85
Compiler resolves
square (‘a’) to
square(char)
3. A MATCH THROUGH APPLICATION OF STANDARD C++ CONVERSION
RULES
If no exact match or match through a promotion is
found, an attempt is made to achieve a match
through a standard conversion of the actual
argument. Consider the following example,
void afunc (char);
afunc (471);
//match through standard
conversion matches afunc (char)
87
‘int’ argument is converted to char
88 88
Error ambiguous call
89 89
4. A MATCH THROUGH APPLICATION OF A USER-DEFINED CONVERSION
If all the above mentioned steps fail, then the
compiler will try the user-defined conversion in
the combinations to find a unique match.
90 90
DEFAULT ARGUMENTS VERSUS OVERLOADING
Using default argument is also overloading,
because the function may be called with an
optional number of arguments.
For instance, consider the following function
prototype:
float amount (float principal, int time=2,
float rate=0.08);
91 91
Now this function may be called by providing just one
or two or all three argument values. A function call
like as follows:
cout<<amount (3000);
will invoke the function amount() with argument
values 3000, 2, and 0.08 respectively. Similarly a
function call like
cout <<amount (3000,4);
Will invoke amount() with argument values 3000, 4
and 0.08
cout <<amount (2500,5,0.12);
Will invoke amount() with argument values 2500, 5,
and 0.12 respectively
92 92
93