SlideShare ist ein Scribd-Unternehmen logo
1 von 70
Agenda
What is a function?
Types of C++ functions:
Standard functions
User-defined functions
C++ function structure
Function signature
Function body
Declaring and
Implementing C++
functions
Sharing data among
functions through
function parameters
Value parameters
Reference parameters
Const reference
parameters
Scope of variables
Local Variables
Global variable
2
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.
 computeTaxescomputeTaxes to compute the taxes for an employee
 isPrimeisPrime to check whether or not a number is a prime number
A returning value
 The computeTaxesomputeTaxes function may return with a double number
representing the amount of taxes
 The isPrimeisPrime function may return with a Boolean value (true or false)
3
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>
4
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;
}
5
Example of Using
Standard C++ Character Functions
#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions
void main()
{
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";
}
6
Explicit casting
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
7
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 signaturefunction 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
8
What is The Syntactic Structure of a C++
Function?
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>)<return value> <name> (<parameter list>)
The function body is simply a C++ code enclosed
between { }
9
Example of User-defined
C++ Function
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
10
Example of User-defined
C++ Function
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
11
Function
header
Example of User-defined
C++ Function
double computeTax(double income)
{
if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);
return taxes;
}
12
Function
header
Function
body
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
double computeTaxes(double) ;
13
Unnamed
Parameter
Semicolon
;
Why Do We Need Function Signature?
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 the implementation file
For Function Abstraction
By only sharing the function signatures, we have the
liberty to change the implementation details from time
to time to
 Improve function performance
 make the customers focus on the purpose of the function, not its
implementation
14
Example#include <iostream>
#include <string>
using namespace std;
// Function Signature
double getIncome(string);
double computeTaxes(double);
void printTaxes(double);
void main()
{
// Get the income;
double income = getIncome("Please enter the
employee income: ");
// Compute Taxes
double taxes = computeTaxes(income);
// Print employee taxes
printTaxes(taxes);
}
double computeTaxes(double income)
{
if (income<5000) return 0.0;
return 0.07*(income-5000.0);
}
double getIncome(string prompt)
{
cout << prompt;
double income;
cin >> income;
return income;
}
void printTaxes(double taxes)
{
cout << "The taxes is $" << taxes << endl;
}
15
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
16
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
17
TaxesRules Header file
#ifndef _TAXES_RULES_
#define _TAXES_RULES_
#include <iostream>
#include <string>
using namespace std;
double getIncome(string);
// purpose -- to get the employee
income
// input -- a string prompt to be
displayed to the user
// output -- a double value
representing the income
double computeTaxes(double);
// purpose -- to compute the taxes for
a given income
// input -- a double value
representing the income
// output -- a double value
representing the taxes
void printTaxes(double);
// purpose -- to display taxes to the
user
// input -- a double value
representing the taxes
// output -- None
#endif
18
TaxesRules Implementation File
#include "TaxesRules.h"
double computeTaxes(double income)
{
if (income<5000) return 0.0;
return 0.07*(income-5000.0);
}
double getIncome(string prompt)
{
cout << prompt;
double income;
cin >> income;
return income;
}
void printTaxes(double taxes)
{
cout << "The taxes is $" << taxes <<
endl;
}
19
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);
// Print employee taxes
printTaxes(taxes);
}
20
Inline Functions
Sometimes, we use the keyword inlineinline 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
inlineinline double degrees( double radian)
{
return radian * 180.0 / 3.1415;
}
21
Example #1Write a function to test if a number is an odd number
inline bool odd (int x)
{
return (x % 2 == 1);
}
22
Example #2
Write a function to compute the distance
between two points (x1, y1) and (x2, y2)
Inline double distance (double x1, double y1,
double x2, double y2)
{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}
23
Example #3
Write a function to compute n!
int factorial( int n)
{
int product=1;
for (int i=1; i<=n; i++) product *= i;
return product;
}
24
Example #4
Function Overloading
Write functions to return with the maximum number of
two numbers
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;
}
25
An overloaded
function is a
function that is
defined more than
once with different
data types or
different number
of parameters
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
26
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
27
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
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
x 0
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
30
x 0
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
31
x 0
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
2
4
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
32
45x
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
3
void f1()void f1()
{{
x++;x++;
}}
4
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
33
45x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}
3
void f1()void f1()
{{
x++;x++;
}}5
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
34
45x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}6
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
35
45x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
7
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
36
45x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}8
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
37
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline 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;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
39
0x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
1
The inline keyword
instructs the compiler
to replace the function
call with the function
body!
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
40
4x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
2
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
41
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
3
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
42
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}4
What Happens When We Use Inline
Keyword?
#include <iostream.h>
int x = 0;
InlineInline void f1() { x++; }
InlineInline void f2() { x+=4; f1();}
void main()
{
f2();
cout << x << endl;
}
43
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!)
44
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
45
Example of Defining and Using Global
and Local Variables#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
46
Example of Defining and Using Global
and Local Variables#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
47
x 0
Global variables are
automatically initialized to 0
Example of Defining and Using Global
and Local Variables#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
48
x 0
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
1
Example of Defining and Using Global
and Local Variables#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
49
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x ????
3
Example of Defining and Using Global
and Local Variables#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
50
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
3
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
51
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
4
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
52
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
2
void fun()void fun()
{{
int x = 10;int x = 10;
cout << x << endl;cout << x << endl;
}}
x 10
5
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
53
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
6
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable// Global variable
Void fun(); // function signature// function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable// Local variable
cout << x << endl;
}
54
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}7
II. Using ParametersFunction Parameters come in three flavors:
Value parametersValue parameters – which copy the values of the
function arguments
Reference parametersReference 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 parametersConstant reference parameters – similar to the reference
parameters but cannot change the values of the
referenced arguments
55
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)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),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),max( a+b, b/2), the values 50 and
5 are copies to x and y respectively
Once the value parameters accepted copies of the
corresponding arguments data, they act as local variables!
56
Example of Using Value Parameters and
Global Variables#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
57
x 0
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
1
Example of Using Value Parameters and
Global Variables
#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
58
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
3
3
Example of Using Value Parameters and
Global Variables
#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
59
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
3
4
8
Example of Using Value Parameters and
Global Variables
#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
60
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
2
void fun(int x )void fun(int x )
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
38
5
Example of Using Value Parameters and
Global Variables
#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
61
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
6
Example of Using Value Parameters and
Global Variables
#include <iostream.h>
int x; // Global variable// Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
62
x 4
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}7
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);
63
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable// Local variable
fun(x);
cout << x << endl;
}
64
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
1 x? x4
Example of Reference Parameters
#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;
}
65
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x4
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}
3
Example of Reference Parameters
#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;
}
66
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x4
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}
4 9
Example of Reference Parameters
#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;
}
67
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
2
x? x9
void fun( int & y )void fun( int & y )
{{
cout<<y<<endl;cout<<y<<endl;
y=y+5;y=y+5;
}}5
Example of Reference Parameters
#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;
}
68
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
6
x? x9
Example of Reference Parameters
#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;
}
69
void main()void main()
{{
int x = 4;int x = 4;
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
x? x9
7
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 (constconst 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
70

Weitere ähnliche Inhalte

Was ist angesagt?

Function class in c++
Function class in c++Function class in c++
Function class in c++
Kumar
 

Was ist angesagt? (19)

C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function class in c++
Function class in c++Function class in c++
Function class in c++
 
Functions in C++ (OOP)
Functions in C++ (OOP)Functions in C++ (OOP)
Functions in C++ (OOP)
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Function C++
Function C++ Function C++
Function C++
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 

Andere mochten auch

Project: Ana & Paloma
Project: Ana & PalomaProject: Ana & Paloma
Project: Ana & Paloma
anapaloma94
 
Vocabulary: Ana & Paloma
Vocabulary: Ana & PalomaVocabulary: Ana & Paloma
Vocabulary: Ana & Paloma
anapaloma94
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library Function
Deepak Singh
 
The Essential School's Guide to Adaptive Learning
The Essential School's Guide to Adaptive LearningThe Essential School's Guide to Adaptive Learning
The Essential School's Guide to Adaptive Learning
Lorna Keane
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
Frankie Jones
 

Andere mochten auch (20)

functions of C++
functions of C++functions of C++
functions of C++
 
Filelist
FilelistFilelist
Filelist
 
Headerfiles
HeaderfilesHeaderfiles
Headerfiles
 
Project: Ana & Paloma
Project: Ana & PalomaProject: Ana & Paloma
Project: Ana & Paloma
 
Vocabulary: Ana & Paloma
Vocabulary: Ana & PalomaVocabulary: Ana & Paloma
Vocabulary: Ana & Paloma
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library Function
 
writting skills
writting skillswritting skills
writting skills
 
Bw
BwBw
Bw
 
The Essential School's Guide to Adaptive Learning
The Essential School's Guide to Adaptive LearningThe Essential School's Guide to Adaptive Learning
The Essential School's Guide to Adaptive Learning
 
Character building
Character buildingCharacter building
Character building
 
Basic communication skills
Basic communication skillsBasic communication skills
Basic communication skills
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
 
8 header files
8 header files8 header files
8 header files
 
Keys to good documentation
Keys to good documentationKeys to good documentation
Keys to good documentation
 
Effective writting skills
Effective writting skillsEffective writting skills
Effective writting skills
 
Functions
FunctionsFunctions
Functions
 
Type header file in c++ and its function
Type header file in c++ and its functionType header file in c++ and its function
Type header file in c++ and its function
 
C++ programming (Array)
C++ programming (Array)C++ programming (Array)
C++ programming (Array)
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Array in c++
Array in c++Array in c++
Array in c++
 

Ähnlich wie C++ functions

introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdf
SameerKhanPathan7
 

Ähnlich wie C++ functions (20)

C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
power point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions conceptspower point presentation on object oriented programming functions concepts
power point presentation on object oriented programming functions concepts
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
C++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
cpp-streams.ppt,C++ is the top choice of many programmers for creating powerf...
 
Chap 2 c++
Chap 2 c++Chap 2 c++
Chap 2 c++
 
introductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdfintroductiontoc-140704113737-phpapp01.pdf
introductiontoc-140704113737-phpapp01.pdf
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Functionincprogram
FunctionincprogramFunctionincprogram
Functionincprogram
 

Kürzlich hochgeladen

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Kürzlich hochgeladen (20)

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

C++ functions

  • 1.
  • 2. Agenda What is a function? Types of C++ functions: Standard functions User-defined functions C++ function structure Function signature Function body Declaring and Implementing C++ functions Sharing data among functions through function parameters Value parameters Reference parameters Const reference parameters Scope of variables Local Variables Global variable 2
  • 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.  computeTaxescomputeTaxes to compute the taxes for an employee  isPrimeisPrime to check whether or not a number is a prime number A returning value  The computeTaxesomputeTaxes function may return with a double number representing the amount of taxes  The isPrimeisPrime function may return with a Boolean value (true or false) 3
  • 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> 4
  • 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; } 5
  • 6. Example of Using Standard C++ Character Functions #include <iostream.h> // input/output handling #include <ctype.h> // character type functions void main() { 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"; } 6 Explicit casting
  • 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 7
  • 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 signaturefunction 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 8
  • 9. What is The Syntactic Structure of a C++ Function? 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>)<return value> <name> (<parameter list>) The function body is simply a C++ code enclosed between { } 9
  • 10. Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 10
  • 11. Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 11 Function header
  • 12. Example of User-defined C++ Function double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes; } 12 Function header Function body
  • 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 Example double computeTaxes(double) ; 13 Unnamed Parameter Semicolon ;
  • 14. Why Do We Need Function Signature? 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 the implementation file For Function Abstraction By only sharing the function signatures, we have the liberty to change the implementation details from time to time to  Improve function performance  make the customers focus on the purpose of the function, not its implementation 14
  • 15. Example#include <iostream> #include <string> using namespace std; // Function Signature double getIncome(string); double computeTaxes(double); void printTaxes(double); void main() { // Get the income; double income = getIncome("Please enter the employee income: "); // Compute Taxes double taxes = computeTaxes(income); // Print employee taxes printTaxes(taxes); } double computeTaxes(double income) { if (income<5000) return 0.0; return 0.07*(income-5000.0); } double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income; } void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; } 15
  • 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 16
  • 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 17
  • 18. TaxesRules Header file #ifndef _TAXES_RULES_ #define _TAXES_RULES_ #include <iostream> #include <string> using namespace std; double getIncome(string); // purpose -- to get the employee income // input -- a string prompt to be displayed to the user // output -- a double value representing the income double computeTaxes(double); // purpose -- to compute the taxes for a given income // input -- a double value representing the income // output -- a double value representing the taxes void printTaxes(double); // purpose -- to display taxes to the user // input -- a double value representing the taxes // output -- None #endif 18
  • 19. TaxesRules Implementation File #include "TaxesRules.h" double computeTaxes(double income) { if (income<5000) return 0.0; return 0.07*(income-5000.0); } double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income; } void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl; } 19
  • 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); // Print employee taxes printTaxes(taxes); } 20
  • 21. Inline Functions Sometimes, we use the keyword inlineinline 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 inlineinline double degrees( double radian) { return radian * 180.0 / 3.1415; } 21
  • 22. Example #1Write a function to test if a number is an odd number inline bool odd (int x) { return (x % 2 == 1); } 22
  • 23. Example #2 Write a function to compute the distance between two points (x1, y1) and (x2, y2) Inline double distance (double x1, double y1, double x2, double y2) { return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); } 23
  • 24. Example #3 Write a function to compute n! int factorial( int n) { int product=1; for (int i=1; i<=n; i++) product *= i; return product; } 24
  • 25. Example #4 Function Overloading Write functions to return with the maximum number of two numbers 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; } 25 An overloaded function is a function that is defined more than once with different data types or different number of parameters
  • 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 26
  • 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 27
  • 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; } 28
  • 29. 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 x 0
  • 30. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 30 x 0 void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1
  • 31. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 31 x 0 void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 2 4
  • 32. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 32 45x void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 3 void f1()void f1() {{ x++;x++; }} 4
  • 33. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 33 45x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }} 3 void f1()void f1() {{ x++;x++; }}5
  • 34. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 34 45x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 1 void f2()void f2() {{ x += 4;x += 4; f1();f1(); }}6
  • 35. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 35 45x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 7
  • 36. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 36 45x void main()void main() {{ f2();f2(); cout << x << endl;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; } 37
  • 38. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 38
  • 39. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 39 0x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 1 The inline keyword instructs the compiler to replace the function call with the function body!
  • 40. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 40 4x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 2
  • 41. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 41 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 3
  • 42. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 42 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }}4
  • 43. What Happens When We Use Inline Keyword? #include <iostream.h> int x = 0; InlineInline void f1() { x++; } InlineInline void f2() { x+=4; f1();} void main() { f2(); cout << x << endl; } 43
  • 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!) 44
  • 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 45
  • 46. Example of Defining and Using Global and Local Variables#include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 46
  • 47. Example of Defining and Using Global and Local Variables#include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 47 x 0 Global variables are automatically initialized to 0
  • 48. Example of Defining and Using Global and Local Variables#include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 48 x 0 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 1
  • 49. Example of Defining and Using Global and Local Variables#include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 49 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x ???? 3
  • 50. Example of Defining and Using Global and Local Variables#include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 50 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 3
  • 51. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 51 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 4
  • 52. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 52 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 2 void fun()void fun() {{ int x = 10;int x = 10; cout << x << endl;cout << x << endl; }} x 10 5
  • 53. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 53 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 6
  • 54. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable// Global variable Void fun(); // function signature// function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable// Local variable cout << x << endl; } 54 x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }}7
  • 55. II. Using ParametersFunction Parameters come in three flavors: Value parametersValue parameters – which copy the values of the function arguments Reference parametersReference 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 parametersConstant reference parameters – similar to the reference parameters but cannot change the values of the referenced arguments 55
  • 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)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),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),max( a+b, b/2), the values 50 and 5 are copies to x and y respectively Once the value parameters accepted copies of the corresponding arguments data, they act as local variables! 56
  • 57. Example of Using Value Parameters and Global Variables#include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 57 x 0 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 1
  • 58. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 58 x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 3 3
  • 59. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 59 x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 3 4 8
  • 60. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 60 x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 2 void fun(int x )void fun(int x ) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} 38 5
  • 61. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 61 x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 6
  • 62. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable// Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 62 x 4 void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;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); 63
  • 64. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable// Local variable fun(x); cout << x << endl; } 64 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 1 x? x4
  • 65. Example of Reference Parameters #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; } 65 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x4 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }} 3
  • 66. Example of Reference Parameters #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; } 66 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x4 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }} 4 9
  • 67. Example of Reference Parameters #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; } 67 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 2 x? x9 void fun( int & y )void fun( int & y ) {{ cout<<y<<endl;cout<<y<<endl; y=y+5;y=y+5; }}5
  • 68. Example of Reference Parameters #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; } 68 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} 6 x? x9
  • 69. Example of Reference Parameters #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; } 69 void main()void main() {{ int x = 4;int x = 4; fun(x);fun(x); cout << x << endl;cout << x << endl; }} x? x9 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 (constconst 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 70