SlideShare a Scribd company logo
1 of 71
C++ FunctionsC++ Functions
By
SATHISHKUMAR G
(sathishsak111@gmail.com)
AgendaAgenda
 What is a function?What is a function?
 Types of C++Types of C++
functions:functions:
 Standard functionsStandard functions
 User-defined functionsUser-defined functions
 C++ function structureC++ function structure
 Function signatureFunction signature
 Function bodyFunction body
 Declaring andDeclaring and
Implementing C++Implementing C++
functionsfunctions
 Sharing data amongSharing data among
functions throughfunctions through
function parametersfunction parameters
 Value parametersValue parameters
 Reference parametersReference parameters
 Const referenceConst reference
parametersparameters
 Scope of variablesScope of variables
 Local VariablesLocal Variables
 Global variableGlobal variable
Functions and subprogramsFunctions and subprograms
 The Top-down design appeoach is based on dividing theThe Top-down design appeoach is based on dividing the
main problem into smaller tasks which may be dividedmain problem into smaller tasks which may be divided
into simpler tasks, then implementing each simple taskinto simpler tasks, then implementing each simple task
by a subprogram or a functionby a subprogram or a function
 A C++ function or a subprogram is simply a chunk of C+A C++ function or a subprogram is simply a chunk of C+
+ code that has+ code that has
 A descriptive function name, e.g.A descriptive function name, e.g.
 computeTaxescomputeTaxes to compute the taxes for an employeeto compute the taxes for an employee
 isPrimeisPrime to check whether or not a number is a prime numberto check whether or not a number is a prime number
 A returning valueA returning value
 The cThe computeTaxesomputeTaxes function may return with a double numberfunction may return with a double number
representing the amount of taxesrepresenting the amount of taxes
 TheThe isPrimeisPrime function may return with a Boolean value (true or false)function may return with a Boolean value (true or false)
C++ Standard FunctionsC++ Standard Functions
 C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions
which are known as standard functionswhich are known as standard functions
 These standard functions are groups in differentThese standard functions are groups in different
libraries which can be included in the C++libraries which can be included in the C++
program, e.g.program, e.g.
 Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library
 Character-manipulation functions are declared inCharacter-manipulation functions are declared in
<ctype.h> library<ctype.h> library
 C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries,
some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h>
and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain
hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>
Example of UsingExample of Using
Standard C++ Math FunctionsStandard C++ Math Functions
#include <iostream.h>#include <iostream.h>
#include <math.h>#include <math.h>
void main()void main()
{{
// Getting a double value// Getting a double value
double x;double x;
cout << "Please enter a real number: ";cout << "Please enter a real number: ";
cin >> x;cin >> x;
// Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number
cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl;
cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl;
}}
Example of UsingExample of Using
Standard C++ Character FunctionsStandard C++ Character Functions
#include <iostream.h> // input/output handling#include <iostream.h> // input/output handling
#include <ctype.h> // character type functions#include <ctype.h> // character type functions
void main()void main()
{{
char ch;char ch;
cout << "Enter a character: ";cout << "Enter a character: ";
cin >> ch;cin >> ch;
cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;
cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;
if (isdigit(ch))if (isdigit(ch))
cout << "'" << ch <<"' is a digit!n";cout << "'" << ch <<"' is a digit!n";
elseelse
cout << "'" << ch <<"' is NOT a digit!n";cout << "'" << ch <<"' is NOT a digit!n";
}}
Explicit casting
User-Defined C++ FunctionsUser-Defined C++ Functions
 Although C++ is shipped with a lot of standardAlthough C++ is shipped with a lot of standard
functions, these functions are not enough for allfunctions, these functions are not enough for all
users, therefore, C++ provides its users with ausers, therefore, C++ provides its users with a
way to define their own functions (or user-way to define their own functions (or user-
defined function)defined function)
 For example, the <math.h> library does notFor example, the <math.h> library does not
include a standard function that allows users toinclude a standard function that allows users to
round a real number to the iround a real number to the ithth
digits, therefore, wedigits, therefore, we
must declare and implement this functionmust declare and implement this function
ourselvesourselves
How to define a C++ Function?How to define a C++ Function?
 Generally speaking, we define a C++Generally speaking, we define a C++
function in two steps (preferably but notfunction in two steps (preferably but not
mandatory)mandatory)
Step #1 – declare theStep #1 – declare the function signaturefunction signature inin
either a header file (.h file) or before the maineither a header file (.h file) or before the main
function of the programfunction of the program
Step #2 – Implement the function in either anStep #2 – Implement the function in either an
implementation file (.cpp) or after the mainimplementation file (.cpp) or after the main
functionfunction
What is The Syntactic Structure ofWhat is The Syntactic Structure of
a C++ Function?a C++ Function?
 A C++ function consists of two partsA C++ function consists of two parts
The function header, andThe function header, and
The function bodyThe function body
 The function header has the followingThe function header has the following
syntaxsyntax
<return value> <name> (<parameter list>)<return value> <name> (<parameter list>)
 The function body is simply a C++ codeThe function body is simply a C++ code
enclosed between { }enclosed between { }
Example of User-definedExample of User-defined
C++ FunctionC++ Function
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
Example of User-definedExample of User-defined
C++ FunctionC++ Function
Function
header
Example of User-definedExample of User-defined
C++ FunctionC++ Function
double computeTax(double income)double computeTax(double income)
{{
if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0;
double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0);
return taxes;return taxes;
}}
Function
header
Function
body
Function SignatureFunction Signature
 The function signature is actually similar toThe function signature is actually similar to
the function header except in two aspects:the function header except in two aspects:
The parameters’ names may not be specifiedThe parameters’ names may not be specified
in the function signaturein the function signature
The function signature must be ended by aThe function signature must be ended by a
semicolonsemicolon
 ExampleExample
double computeTaxes(double) ;double computeTaxes(double) ;
Unnamed
Parameter
Semicolon
;
Why Do We Need FunctionWhy Do We Need Function
Signature?Signature?
 For Information HidingFor Information Hiding
 If you want to create your own library and share it withIf you want to create your own library and share it with
your customers without letting them know theyour customers without letting them know the
implementation details, you should declare all theimplementation details, you should declare all the
function signatures in a header (.h) file and distributefunction signatures in a header (.h) file and distribute
the binary code of the implementation filethe binary code of the implementation file
 For Function AbstractionFor Function Abstraction
 By only sharing the function signatures, we have theBy only sharing the function signatures, we have the
liberty to change the implementation details from timeliberty to change the implementation details from time
to time toto time to
 Improve function performanceImprove function performance
 make the customers focus on the purpose of the function, notmake the customers focus on the purpose of the function, not
its implementationits implementation
ExampleExample
#include <iostream>#include <iostream>
#include <string>#include <string>
using namespace std;using namespace std;
// Function Signature// Function Signature
double getIncome(string);double getIncome(string);
double computeTaxes(double);double computeTaxes(double);
void printTaxes(double);void printTaxes(double);
void main()void main()
{{
// Get the income;// Get the income;
double income = getIncome("Please enterdouble income = getIncome("Please enter
the employee income: ");the employee income: ");
// Compute Taxes// Compute Taxes
double taxes = computeTaxes(income);double taxes = computeTaxes(income);
// Print employee taxes// Print employee taxes
printTaxes(taxes);printTaxes(taxes);
}}
double computeTaxes(double income)double computeTaxes(double income)
{{
if (income<5000) return 0.0;if (income<5000) return 0.0;
return 0.07*(income-5000.0);return 0.07*(income-5000.0);
}}
double getIncome(string prompt)double getIncome(string prompt)
{{
cout << prompt;cout << prompt;
double income;double income;
cin >> income;cin >> income;
return income;return income;
}}
void printTaxes(double taxes)void printTaxes(double taxes)
{{
cout << "The taxes is $" << taxes << endl;cout << "The taxes is $" << taxes << endl;
}}
Building Your LibrariesBuilding Your Libraries
 It is a good practice to build libraries to beIt is a good practice to build libraries to be
used by you and your customersused by you and your customers
 In order to build C++ libraries, you shouldIn order to build C++ libraries, you should
be familiar withbe familiar with
How to create header files to store functionHow to create header files to store function
signaturessignatures
How to create implementation files to storeHow to create implementation files to store
function implementationsfunction implementations
How to include the header file to yourHow to include the header file to your
program to use your user-defined functionsprogram to use your user-defined functions
C++ Header FilesC++ Header Files
 The C++ header files must have .hThe C++ header files must have .h
extension and should have the followingextension and should have the following
structurestructure
#ifndef compiler directive#ifndef compiler directive
#define compiler directive#define compiler directive
May include some other header filesMay include some other header files
All functions signatures with some commentsAll functions signatures with some comments
about their purposes, their inputs, and outputsabout their purposes, their inputs, and outputs
#endif compiler directive#endif compiler directive
TaxesRules Header fileTaxesRules Header file
#ifndef _TAXES_RULES_#ifndef _TAXES_RULES_
#define _TAXES_RULES_#define _TAXES_RULES_
#include <iostream>#include <iostream>
#include <string>#include <string>
using namespace std;using namespace std;
double getIncome(string);double getIncome(string);
// purpose -- to get the employee// purpose -- to get the employee
incomeincome
// input -- a string prompt to be// input -- a string prompt to be
displayed to the userdisplayed to the user
// output -- a double value// output -- a double value
representing the incomerepresenting the income
double computeTaxes(double);double computeTaxes(double);
// purpose -- to compute the taxes for// purpose -- to compute the taxes for
a given incomea given income
// input -- a double value// input -- a double value
representing the incomerepresenting the income
// output -- a double value// output -- a double value
representing the taxesrepresenting the taxes
void printTaxes(double);void printTaxes(double);
// purpose -- to display taxes to the// purpose -- to display taxes to the
useruser
// input -- a double value// input -- a double value
representing the taxesrepresenting the taxes
// output -- None// output -- None
#endif#endif
TaxesRules Implementation FileTaxesRules Implementation File
#include "TaxesRules.h"#include "TaxesRules.h"
double computeTaxes(doubledouble computeTaxes(double
income)income)
{{
if (income<5000) return 0.0;if (income<5000) return 0.0;
return 0.07*(income-5000.0);return 0.07*(income-5000.0);
}}
double getIncome(string prompt)double getIncome(string prompt)
{{
cout << prompt;cout << prompt;
double income;double income;
cin >> income;cin >> income;
return income;return income;
}}
void printTaxes(double taxes)void printTaxes(double taxes)
{{
cout << "The taxes is $" << taxescout << "The taxes is $" << taxes
<< endl;<< endl;
}}
Main Program FileMain Program File
#include "TaxesRules.h"#include "TaxesRules.h"
void main()void main()
{{
// Get the income;// Get the income;
double income =double income =
getIncome("Please enter the employee income: ");getIncome("Please enter the employee income: ");
// Compute Taxes// Compute Taxes
double taxes = computeTaxes(income);double taxes = computeTaxes(income);
// Print employee taxes// Print employee taxes
printTaxes(taxes);printTaxes(taxes);
}}
Inline FunctionsInline Functions
 Sometimes, we use the keywordSometimes, we use the keyword inlineinline to defineto define
user-defined functionsuser-defined functions
 Inline functions are very small functions, generally,Inline functions are very small functions, generally,
one or two lines of codeone or two lines of code
 Inline functions are very fast functions compared toInline functions are very fast functions compared to
the functions declared without the inline keywordthe functions declared without the inline keyword
 ExampleExample
inlineinline double degrees( double radian)double degrees( double radian)
{{
return radian * 180.0 / 3.1415;return radian * 180.0 / 3.1415;
}}
Example #1Example #1
 Write a function to test if a number is anWrite a function to test if a number is an
odd numberodd number
inline bool odd (int x)inline bool odd (int x)
{{
return (x % 2 == 1);return (x % 2 == 1);
}}
Example #2Example #2
 Write a function to compute the distanceWrite a function to compute the distance
between two points (x1, y1) and (x2, y2)between two points (x1, y1) and (x2, y2)
Inline double distance (double x1, double y1,Inline double distance (double x1, double y1,
double x2, double y2)double x2, double y2)
{{
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}}
Example #3Example #3
 Write a function to compute n!Write a function to compute n!
int factorial( int n)int factorial( int n)
{{
int product=1;int product=1;
for (int i=1; i<=n; i++) product *= i;for (int i=1; i<=n; i++) product *= i;
return product;return product;
}}
Example #4Example #4
Function OverloadingFunction Overloading
 Write functions to return with the maximum number ofWrite functions to return with the maximum number of
two numberstwo numbers
inline int max( int x, int y)inline int max( int x, int y)
{{
if (x>y) return x; else return y;if (x>y) return x; else return y;
}}
inline double max( double x, double y)inline double max( double x, double y)
{{
if (x>y) return x; else return y;if (x>y) return x; else return y;
}}
An overloaded
function is a
function that is
defined more than
once with different
data types or
different number
of parameters
Sharing Data AmongSharing Data Among
User-Defined FunctionsUser-Defined Functions
There are two ways to share dataThere are two ways to share data
among different functionsamong different functions
Using global variables (very bad practice!)Using global variables (very bad practice!)
Passing data through function parametersPassing data through function parameters
Value parametersValue parameters
Reference parametersReference parameters
Constant reference parametersConstant reference parameters
C++ VariablesC++ Variables
 A variable is a place in memory that hasA variable is a place in memory that has
 A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.)
 A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.)
 A size (number of bytes)A size (number of bytes)
 A scope (the part of the program code that can use it)A scope (the part of the program code that can use it)
 Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it
 Local variables – only the function that declare localLocal variables – only the function that declare local
variables see and use these variablesvariables see and use these variables
 A life time (the duration of its existence)A life time (the duration of its existence)
 Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed
 Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define
these variables are executedthese variables are executed
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x 0
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
f2();f2();
cout << x << endl ;cout << x << endl ;
}}
1
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
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
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
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
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
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
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
1
void f2()void f2()
{{
x += 4;x += 4;
f1();f1();
}}6
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
7
45
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
x
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}8
I. Using Global VariablesI. Using Global Variables
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
void f1() { x++; }void f1() { x++; }
void f2() { x+=4; f1(); }void f2() { x+=4; f1(); }
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
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 UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
4x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
2
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}
3
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
5x
void main()void main()
{{
x+=4;x+=4;
x++;x++;
cout << x << endl;cout << x << endl;
}}4
What Happens When We UseWhat Happens When We Use
Inline Keyword?Inline Keyword?
#include <iostream.h>#include <iostream.h>
int x = 0;int x = 0;
InlineInline void f1() { x++; }void f1() { x++; }
InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();}
void main()void main()
{{
f2();f2();
cout << x << endl;cout << x << endl;
}}
What is Bad About UsingWhat is Bad About Using
Global Vairables?Global Vairables?
 Not safe!Not safe!
 If two or more programmers are working together in aIf two or more programmers are working together in a
program, one of them may change the value stored inprogram, one of them may change the value stored in
the global variable without telling the others who maythe global variable without telling the others who may
depend in their calculation on the old stored value!depend in their calculation on the old stored value!
 Against The Principle of Information Hiding!Against The Principle of Information Hiding!
 Exposing the global variables to all functions isExposing the global variables to all functions is
against the principle of information hiding since thisagainst the principle of information hiding since this
gives all functions the freedom to change the valuesgives all functions the freedom to change the values
stored in the global variables at any time (unsafe!)stored in the global variables at any time (unsafe!)
Local VariablesLocal Variables
 Local variables are declared inside the functionLocal variables are declared inside the function
body and exist as long as the function is runningbody and exist as long as the function is running
and destroyed when the function exitand destroyed when the function exit
 You have to initialize the local variable beforeYou have to initialize the local variable before
using itusing it
 If a function defines a local variable and thereIf a function defines a local variable and there
was a global variable with the same name, thewas a global variable with the same name, the
function uses its local variable instead of usingfunction uses its local variable instead of using
the global variablethe global variable
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 0
Global variables are
automatically initialized to 0
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 0
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
1
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
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 UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
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 UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
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 UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
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 UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
6
Example of Defining and UsingExample of Defining and Using
Global and Local VariablesGlobal and Local Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
Void fun();Void fun(); // function signature// function signature
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}
void fun()void fun()
{{
int x = 10;int x = 10; // Local variable// Local variable
cout << x << endl;cout << x << endl;
}}
x 4
void main()void main()
{{
x = 4;x = 4;
fun();fun();
cout << x << endl;cout << x << endl;
}}7
II. Using ParametersII. Using Parameters
 Function Parameters come in threeFunction Parameters come in three
flavors:flavors:
Value parametersValue parameters – which copy the values of– which copy the values of
the function argumentsthe function arguments
Reference parametersReference parameters – which refer to the– which refer to the
function arguments by other local names andfunction arguments by other local names and
have the ability to change the values of thehave the ability to change the values of the
referenced argumentsreferenced arguments
Constant reference parametersConstant reference parameters – similar to– similar to
the reference parameters but cannot changethe reference parameters but cannot change
the values of the referenced argumentsthe values of the referenced arguments
Value ParametersValue Parameters
 This is what we use to declare in the function signature orThis is what we use to declare in the function signature or
function header, e.g.function header, e.g.
int max (int x, int y);int max (int x, int y);
 Here, parameters x and y are value parametersHere, parameters x and y are value parameters
 When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7
are copied to x and y respectivelyare copied to x and y respectively
 When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and
b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively
 When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50
and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively
 Once the value parameters accepted copies of theOnce the value parameters accepted copies of the
corresponding arguments data, they act as localcorresponding arguments data, they act as local
variables!variables!
Example of Using ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ValueExample of Using Value
Parameters and Global VariablesParameters and Global Variables
#include <iostream.h>#include <iostream.h>
int x;int x; // Global variable// Global variable
void fun(int x)void fun(int x)
{{
cout << x << endl;cout << x << endl;
x=x+5;x=x+5;
}}
void main()void main()
{{
x = 4;x = 4;
fun(x/2+1);fun(x/2+1);
cout << x << endl;cout << x << endl;
}}
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 ParametersReference Parameters
 As we saw in the last example, any changes inAs we saw in the last example, any changes in
the value parameters don’t affect the originalthe value parameters don’t affect the original
function argumentsfunction arguments
 Sometimes, we want to change the values of theSometimes, we want to change the values of the
original function arguments or return with moreoriginal function arguments or return with more
than one value from the function, in this case wethan one value from the function, in this case we
use reference parametersuse reference parameters
 A reference parameter is just another name to theA reference parameter is just another name to the
original argument variableoriginal argument variable
 We define a reference parameter by adding the & inWe define a reference parameter by adding the & in
front of the parameter name, e.g.front of the parameter name, e.g.
double update (doubledouble update (double && x);x);
Example of Reference ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4;int x = 4; // Local variable// Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersExample of Reference Parameters
#include <iostream.h>#include <iostream.h>
void fun(int &y)void fun(int &y)
{{
cout << y << endl;cout << y << endl;
y=y+5;y=y+5;
}}
void main()void main()
{{
int x = 4; // Local variableint x = 4; // Local variable
fun(x);fun(x);
cout << x << endl;cout << x << endl;
}}
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 ParametersConstant Reference Parameters
 Constant reference parameters are used underConstant reference parameters are used under
the following two conditions:the following two conditions:
 The passed data are so big and you want to saveThe passed data are so big and you want to save
time and computer memorytime and computer memory
 The passed data will not be changed or updated inThe passed data will not be changed or updated in
the function bodythe function body
 For exampleFor example
void report (void report (constconst stringstring && prompt);prompt);
 The only valid arguments accepted by referenceThe only valid arguments accepted by reference
parameters and constant reference parametersparameters and constant reference parameters
are variable namesare variable names
 It is a syntax error to pass constant values orIt is a syntax error to pass constant values or
expressions to the (const) reference parametersexpressions to the (const) reference parameters
Thank youThank you

More Related Content

What's hot

Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaEdureka!
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsEng Teong Cheah
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++Maliha Mehr
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methodsnarmadhakin
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 

What's hot (20)

C functions
C functionsC functions
C functions
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Python functions
Python functionsPython functions
Python functions
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
user defined function
user defined functionuser defined function
user defined function
 
Function in C
Function in CFunction in C
Function in C
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
 
Learn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & MethodsLearn C# Programming - Encapsulation & Methods
Learn C# Programming - Encapsulation & Methods
 
Recursion in C++
Recursion in C++Recursion in C++
Recursion in C++
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Call by value
Call by valueCall by value
Call by value
 
Function in c
Function in cFunction in c
Function in c
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 

Similar to C++ Functions

Similar to C++ Functions (20)

C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
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++ Overview PPT
C++ Overview PPTC++ Overview PPT
C++ Overview PPT
 
C++
C++C++
C++
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Introduction to c++
Introduction to c++Introduction to c++
Introduction to c++
 
CPP-overviews notes variable data types notes
CPP-overviews notes variable data types notesCPP-overviews notes variable data types notes
CPP-overviews notes variable data types notes
 
cppt-170218053903 (1).pptx
cppt-170218053903 (1).pptxcppt-170218053903 (1).pptx
cppt-170218053903 (1).pptx
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Bcsl 031 solve assignment
Bcsl 031 solve assignmentBcsl 031 solve assignment
Bcsl 031 solve assignment
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Programming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptxProgramming For Engineers Functions - Part #1.pptx
Programming For Engineers Functions - Part #1.pptx
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 

More from sathish sak

TRANSPARENT CONCRE
TRANSPARENT CONCRETRANSPARENT CONCRE
TRANSPARENT CONCREsathish sak
 
Stationary Waves
Stationary WavesStationary Waves
Stationary Wavessathish sak
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heartsathish sak
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heartsathish sak
 
Software process life cycles
Software process life cyclesSoftware process life cycles
Software process life cycles sathish sak
 
Digital Logic Circuits
Digital Logic CircuitsDigital Logic Circuits
Digital Logic Circuitssathish sak
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Schedulingsathish sak
 
Real-Time Signal Processing: Implementation and Application
Real-Time Signal Processing:  Implementation and ApplicationReal-Time Signal Processing:  Implementation and Application
Real-Time Signal Processing: Implementation and Applicationsathish sak
 
DIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWDIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWsathish sak
 
FRACTAL ROBOTICS
FRACTAL  ROBOTICSFRACTAL  ROBOTICS
FRACTAL ROBOTICSsathish sak
 
POWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTPOWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTsathish sak
 
mathematics application fiels of engineering
mathematics application fiels of engineeringmathematics application fiels of engineering
mathematics application fiels of engineeringsathish sak
 
ENVIRONMENTAL POLLUTION
ENVIRONMENTALPOLLUTIONENVIRONMENTALPOLLUTION
ENVIRONMENTAL POLLUTIONsathish sak
 

More from sathish sak (20)

TRANSPARENT CONCRE
TRANSPARENT CONCRETRANSPARENT CONCRE
TRANSPARENT CONCRE
 
Stationary Waves
Stationary WavesStationary Waves
Stationary Waves
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heart
 
Electrical Activity of the Heart
Electrical Activity of the HeartElectrical Activity of the Heart
Electrical Activity of the Heart
 
Software process life cycles
Software process life cyclesSoftware process life cycles
Software process life cycles
 
Digital Logic Circuits
Digital Logic CircuitsDigital Logic Circuits
Digital Logic Circuits
 
Real-Time Scheduling
Real-Time SchedulingReal-Time Scheduling
Real-Time Scheduling
 
Real-Time Signal Processing: Implementation and Application
Real-Time Signal Processing:  Implementation and ApplicationReal-Time Signal Processing:  Implementation and Application
Real-Time Signal Processing: Implementation and Application
 
DIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEWDIGITAL SIGNAL PROCESSOR OVERVIEW
DIGITAL SIGNAL PROCESSOR OVERVIEW
 
FRACTAL ROBOTICS
FRACTAL  ROBOTICSFRACTAL  ROBOTICS
FRACTAL ROBOTICS
 
Electro bike
Electro bikeElectro bike
Electro bike
 
ROBOTIC SURGERY
ROBOTIC SURGERYROBOTIC SURGERY
ROBOTIC SURGERY
 
POWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANTPOWER GENERATION OF THERMAL POWER PLANT
POWER GENERATION OF THERMAL POWER PLANT
 
mathematics application fiels of engineering
mathematics application fiels of engineeringmathematics application fiels of engineering
mathematics application fiels of engineering
 
Plastics…
Plastics…Plastics…
Plastics…
 
ENGINEERING
ENGINEERINGENGINEERING
ENGINEERING
 
ENVIRONMENTAL POLLUTION
ENVIRONMENTALPOLLUTIONENVIRONMENTALPOLLUTION
ENVIRONMENTAL POLLUTION
 
RFID TECHNOLOGY
RFID TECHNOLOGYRFID TECHNOLOGY
RFID TECHNOLOGY
 
green chemistry
green chemistrygreen chemistry
green chemistry
 
NANOTECHNOLOGY
  NANOTECHNOLOGY	  NANOTECHNOLOGY
NANOTECHNOLOGY
 

Recently uploaded

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 

Recently uploaded (20)

Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 

C++ Functions

  • 1. C++ FunctionsC++ Functions By SATHISHKUMAR G (sathishsak111@gmail.com)
  • 2. AgendaAgenda  What is a function?What is a function?  Types of C++Types of C++ functions:functions:  Standard functionsStandard functions  User-defined functionsUser-defined functions  C++ function structureC++ function structure  Function signatureFunction signature  Function bodyFunction body  Declaring andDeclaring and Implementing C++Implementing C++ functionsfunctions  Sharing data amongSharing data among functions throughfunctions through function parametersfunction parameters  Value parametersValue parameters  Reference parametersReference parameters  Const referenceConst reference parametersparameters  Scope of variablesScope of variables  Local VariablesLocal Variables  Global variableGlobal variable
  • 3. Functions and subprogramsFunctions and subprograms  The Top-down design appeoach is based on dividing theThe Top-down design appeoach is based on dividing the main problem into smaller tasks which may be dividedmain problem into smaller tasks which may be divided into simpler tasks, then implementing each simple taskinto simpler tasks, then implementing each simple task by a subprogram or a functionby a subprogram or a function  A C++ function or a subprogram is simply a chunk of C+A C++ function or a subprogram is simply a chunk of C+ + code that has+ code that has  A descriptive function name, e.g.A descriptive function name, e.g.  computeTaxescomputeTaxes to compute the taxes for an employeeto compute the taxes for an employee  isPrimeisPrime to check whether or not a number is a prime numberto check whether or not a number is a prime number  A returning valueA returning value  The cThe computeTaxesomputeTaxes function may return with a double numberfunction may return with a double number representing the amount of taxesrepresenting the amount of taxes  TheThe isPrimeisPrime function may return with a Boolean value (true or false)function may return with a Boolean value (true or false)
  • 4. C++ Standard FunctionsC++ Standard Functions  C++ language is shipped with a lot of functionsC++ language is shipped with a lot of functions which are known as standard functionswhich are known as standard functions  These standard functions are groups in differentThese standard functions are groups in different libraries which can be included in the C++libraries which can be included in the C++ program, e.g.program, e.g.  Math functions are declared in <math.h> libraryMath functions are declared in <math.h> library  Character-manipulation functions are declared inCharacter-manipulation functions are declared in <ctype.h> library<ctype.h> library  C++ is shipped with more than 100 standard libraries,C++ is shipped with more than 100 standard libraries, some of them are very popular such as <iostream.h>some of them are very popular such as <iostream.h> and <stdlib.h>, others are very specific to certainand <stdlib.h>, others are very specific to certain hardware platform, e.g. <limits.h> and <largeInt.h>hardware platform, e.g. <limits.h> and <largeInt.h>
  • 5. Example of UsingExample of Using Standard C++ Math FunctionsStandard C++ Math Functions #include <iostream.h>#include <iostream.h> #include <math.h>#include <math.h> void main()void main() {{ // Getting a double value// Getting a double value double x;double x; cout << "Please enter a real number: ";cout << "Please enter a real number: "; cin >> x;cin >> x; // Compute the ceiling and the floor of the real number// Compute the ceiling and the floor of the real number cout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The ceil(" << x << ") = " << ceil(x) << endl; cout << "The floor(" << x << ") = " << floor(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl; }}
  • 6. Example of UsingExample of Using Standard C++ Character FunctionsStandard C++ Character Functions #include <iostream.h> // input/output handling#include <iostream.h> // input/output handling #include <ctype.h> // character type functions#include <ctype.h> // character type functions void main()void main() {{ char ch;char ch; cout << "Enter a character: ";cout << "Enter a character: "; cin >> ch;cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl; cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl; if (isdigit(ch))if (isdigit(ch)) cout << "'" << ch <<"' is a digit!n";cout << "'" << ch <<"' is a digit!n"; elseelse cout << "'" << ch <<"' is NOT a digit!n";cout << "'" << ch <<"' is NOT a digit!n"; }} Explicit casting
  • 7. User-Defined C++ FunctionsUser-Defined C++ Functions  Although C++ is shipped with a lot of standardAlthough C++ is shipped with a lot of standard functions, these functions are not enough for allfunctions, these functions are not enough for all users, therefore, C++ provides its users with ausers, therefore, C++ provides its users with a way to define their own functions (or user-way to define their own functions (or user- defined function)defined function)  For example, the <math.h> library does notFor example, the <math.h> library does not include a standard function that allows users toinclude a standard function that allows users to round a real number to the iround a real number to the ithth digits, therefore, wedigits, therefore, we must declare and implement this functionmust declare and implement this function ourselvesourselves
  • 8. How to define a C++ Function?How to define a C++ Function?  Generally speaking, we define a C++Generally speaking, we define a C++ function in two steps (preferably but notfunction in two steps (preferably but not mandatory)mandatory) Step #1 – declare theStep #1 – declare the function signaturefunction signature inin either a header file (.h file) or before the maineither a header file (.h file) or before the main function of the programfunction of the program Step #2 – Implement the function in either anStep #2 – Implement the function in either an implementation file (.cpp) or after the mainimplementation file (.cpp) or after the main functionfunction
  • 9. What is The Syntactic Structure ofWhat is The Syntactic Structure of a C++ Function?a C++ Function?  A C++ function consists of two partsA C++ function consists of two parts The function header, andThe function header, and The function bodyThe function body  The function header has the followingThe function header has the following syntaxsyntax <return value> <name> (<parameter list>)<return value> <name> (<parameter list>)  The function body is simply a C++ codeThe function body is simply a C++ code enclosed between { }enclosed between { }
  • 10. Example of User-definedExample of User-defined C++ FunctionC++ Function double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }}
  • 11. double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }} Example of User-definedExample of User-defined C++ FunctionC++ Function Function header
  • 12. Example of User-definedExample of User-defined C++ FunctionC++ Function double computeTax(double income)double computeTax(double income) {{ if (income < 5000.0) return 0.0;if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0);double taxes = 0.07 * (income-5000.0); return taxes;return taxes; }} Function header Function body
  • 13. Function SignatureFunction Signature  The function signature is actually similar toThe function signature is actually similar to the function header except in two aspects:the function header except in two aspects: The parameters’ names may not be specifiedThe parameters’ names may not be specified in the function signaturein the function signature The function signature must be ended by aThe function signature must be ended by a semicolonsemicolon  ExampleExample double computeTaxes(double) ;double computeTaxes(double) ; Unnamed Parameter Semicolon ;
  • 14. Why Do We Need FunctionWhy Do We Need Function Signature?Signature?  For Information HidingFor Information Hiding  If you want to create your own library and share it withIf you want to create your own library and share it with your customers without letting them know theyour customers without letting them know the implementation details, you should declare all theimplementation details, you should declare all the function signatures in a header (.h) file and distributefunction signatures in a header (.h) file and distribute the binary code of the implementation filethe binary code of the implementation file  For Function AbstractionFor Function Abstraction  By only sharing the function signatures, we have theBy only sharing the function signatures, we have the liberty to change the implementation details from timeliberty to change the implementation details from time to time toto time to  Improve function performanceImprove function performance  make the customers focus on the purpose of the function, notmake the customers focus on the purpose of the function, not its implementationits implementation
  • 15. ExampleExample #include <iostream>#include <iostream> #include <string>#include <string> using namespace std;using namespace std; // Function Signature// Function Signature double getIncome(string);double getIncome(string); double computeTaxes(double);double computeTaxes(double); void printTaxes(double);void printTaxes(double); void main()void main() {{ // Get the income;// Get the income; double income = getIncome("Please enterdouble income = getIncome("Please enter the employee income: ");the employee income: "); // Compute Taxes// Compute Taxes double taxes = computeTaxes(income);double taxes = computeTaxes(income); // Print employee taxes// Print employee taxes printTaxes(taxes);printTaxes(taxes); }} double computeTaxes(double income)double computeTaxes(double income) {{ if (income<5000) return 0.0;if (income<5000) return 0.0; return 0.07*(income-5000.0);return 0.07*(income-5000.0); }} double getIncome(string prompt)double getIncome(string prompt) {{ cout << prompt;cout << prompt; double income;double income; cin >> income;cin >> income; return income;return income; }} void printTaxes(double taxes)void printTaxes(double taxes) {{ cout << "The taxes is $" << taxes << endl;cout << "The taxes is $" << taxes << endl; }}
  • 16. Building Your LibrariesBuilding Your Libraries  It is a good practice to build libraries to beIt is a good practice to build libraries to be used by you and your customersused by you and your customers  In order to build C++ libraries, you shouldIn order to build C++ libraries, you should be familiar withbe familiar with How to create header files to store functionHow to create header files to store function signaturessignatures How to create implementation files to storeHow to create implementation files to store function implementationsfunction implementations How to include the header file to yourHow to include the header file to your program to use your user-defined functionsprogram to use your user-defined functions
  • 17. C++ Header FilesC++ Header Files  The C++ header files must have .hThe C++ header files must have .h extension and should have the followingextension and should have the following structurestructure #ifndef compiler directive#ifndef compiler directive #define compiler directive#define compiler directive May include some other header filesMay include some other header files All functions signatures with some commentsAll functions signatures with some comments about their purposes, their inputs, and outputsabout their purposes, their inputs, and outputs #endif compiler directive#endif compiler directive
  • 18. TaxesRules Header fileTaxesRules Header file #ifndef _TAXES_RULES_#ifndef _TAXES_RULES_ #define _TAXES_RULES_#define _TAXES_RULES_ #include <iostream>#include <iostream> #include <string>#include <string> using namespace std;using namespace std; double getIncome(string);double getIncome(string); // purpose -- to get the employee// purpose -- to get the employee incomeincome // input -- a string prompt to be// input -- a string prompt to be displayed to the userdisplayed to the user // output -- a double value// output -- a double value representing the incomerepresenting the income double computeTaxes(double);double computeTaxes(double); // purpose -- to compute the taxes for// purpose -- to compute the taxes for a given incomea given income // input -- a double value// input -- a double value representing the incomerepresenting the income // output -- a double value// output -- a double value representing the taxesrepresenting the taxes void printTaxes(double);void printTaxes(double); // purpose -- to display taxes to the// purpose -- to display taxes to the useruser // input -- a double value// input -- a double value representing the taxesrepresenting the taxes // output -- None// output -- None #endif#endif
  • 19. TaxesRules Implementation FileTaxesRules Implementation File #include "TaxesRules.h"#include "TaxesRules.h" double computeTaxes(doubledouble computeTaxes(double income)income) {{ if (income<5000) return 0.0;if (income<5000) return 0.0; return 0.07*(income-5000.0);return 0.07*(income-5000.0); }} double getIncome(string prompt)double getIncome(string prompt) {{ cout << prompt;cout << prompt; double income;double income; cin >> income;cin >> income; return income;return income; }} void printTaxes(double taxes)void printTaxes(double taxes) {{ cout << "The taxes is $" << taxescout << "The taxes is $" << taxes << endl;<< endl; }}
  • 20. Main Program FileMain Program File #include "TaxesRules.h"#include "TaxesRules.h" void main()void main() {{ // Get the income;// Get the income; double income =double income = getIncome("Please enter the employee income: ");getIncome("Please enter the employee income: "); // Compute Taxes// Compute Taxes double taxes = computeTaxes(income);double taxes = computeTaxes(income); // Print employee taxes// Print employee taxes printTaxes(taxes);printTaxes(taxes); }}
  • 21. Inline FunctionsInline Functions  Sometimes, we use the keywordSometimes, we use the keyword inlineinline to defineto define user-defined functionsuser-defined functions  Inline functions are very small functions, generally,Inline functions are very small functions, generally, one or two lines of codeone or two lines of code  Inline functions are very fast functions compared toInline functions are very fast functions compared to the functions declared without the inline keywordthe functions declared without the inline keyword  ExampleExample inlineinline double degrees( double radian)double degrees( double radian) {{ return radian * 180.0 / 3.1415;return radian * 180.0 / 3.1415; }}
  • 22. Example #1Example #1  Write a function to test if a number is anWrite a function to test if a number is an odd numberodd number inline bool odd (int x)inline bool odd (int x) {{ return (x % 2 == 1);return (x % 2 == 1); }}
  • 23. Example #2Example #2  Write a function to compute the distanceWrite a function to compute the distance between two points (x1, y1) and (x2, y2)between two points (x1, y1) and (x2, y2) Inline double distance (double x1, double y1,Inline double distance (double x1, double y1, double x2, double y2)double x2, double y2) {{ return sqrt(pow(x1-x2,2)+pow(y1-y2,2));return sqrt(pow(x1-x2,2)+pow(y1-y2,2)); }}
  • 24. Example #3Example #3  Write a function to compute n!Write a function to compute n! int factorial( int n)int factorial( int n) {{ int product=1;int product=1; for (int i=1; i<=n; i++) product *= i;for (int i=1; i<=n; i++) product *= i; return product;return product; }}
  • 25. Example #4Example #4 Function OverloadingFunction Overloading  Write functions to return with the maximum number ofWrite functions to return with the maximum number of two numberstwo numbers inline int max( int x, int y)inline int max( int x, int y) {{ if (x>y) return x; else return y;if (x>y) return x; else return y; }} inline double max( double x, double y)inline double max( double x, double y) {{ if (x>y) return x; else return y;if (x>y) return x; else return y; }} An overloaded function is a function that is defined more than once with different data types or different number of parameters
  • 26. Sharing Data AmongSharing Data Among User-Defined FunctionsUser-Defined Functions There are two ways to share dataThere are two ways to share data among different functionsamong different functions Using global variables (very bad practice!)Using global variables (very bad practice!) Passing data through function parametersPassing data through function parameters Value parametersValue parameters Reference parametersReference parameters Constant reference parametersConstant reference parameters
  • 27. C++ VariablesC++ Variables  A variable is a place in memory that hasA variable is a place in memory that has  A name or identifier (e.g. income, taxes, etc.)A name or identifier (e.g. income, taxes, etc.)  A data type (e.g. int, double, char, etc.)A data type (e.g. int, double, char, etc.)  A size (number of bytes)A size (number of bytes)  A scope (the part of the program code that can use it)A scope (the part of the program code that can use it)  Global variables – all functions can see it and using itGlobal variables – all functions can see it and using it  Local variables – only the function that declare localLocal variables – only the function that declare local variables see and use these variablesvariables see and use these variables  A life time (the duration of its existence)A life time (the duration of its existence)  Global variables can live as long as the program is executedGlobal variables can live as long as the program is executed  Local variables are lived only when the functions that defineLocal variables are lived only when the functions that define these variables are executedthese variables are executed
  • 28. I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 29. I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 0
  • 30. I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ f2();f2(); cout << x << endl ;cout << x << endl ; }} 1
  • 31. I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 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. 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 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. 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 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. 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x 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. 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 7
  • 36. 45 I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} x void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}8
  • 37. I. Using Global VariablesI. Using Global Variables #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; void f1() { x++; }void f1() { x++; } void f2() { x+=4; f1(); }void f2() { x+=4; f1(); } void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 38. What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 39. What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 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 UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 4x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 2
  • 41. What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }} 3
  • 42. What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }} 5x void main()void main() {{ x+=4;x+=4; x++;x++; cout << x << endl;cout << x << endl; }}4
  • 43. What Happens When We UseWhat Happens When We Use Inline Keyword?Inline Keyword? #include <iostream.h>#include <iostream.h> int x = 0;int x = 0; InlineInline void f1() { x++; }void f1() { x++; } InlineInline void f2() { x+=4; f1();}void f2() { x+=4; f1();} void main()void main() {{ f2();f2(); cout << x << endl;cout << x << endl; }}
  • 44. What is Bad About UsingWhat is Bad About Using Global Vairables?Global Vairables?  Not safe!Not safe!  If two or more programmers are working together in aIf two or more programmers are working together in a program, one of them may change the value stored inprogram, one of them may change the value stored in the global variable without telling the others who maythe global variable without telling the others who may depend in their calculation on the old stored value!depend in their calculation on the old stored value!  Against The Principle of Information Hiding!Against The Principle of Information Hiding!  Exposing the global variables to all functions isExposing the global variables to all functions is against the principle of information hiding since thisagainst the principle of information hiding since this gives all functions the freedom to change the valuesgives all functions the freedom to change the values stored in the global variables at any time (unsafe!)stored in the global variables at any time (unsafe!)
  • 45. Local VariablesLocal Variables  Local variables are declared inside the functionLocal variables are declared inside the function body and exist as long as the function is runningbody and exist as long as the function is running and destroyed when the function exitand destroyed when the function exit  You have to initialize the local variable beforeYou have to initialize the local variable before using itusing it  If a function defines a local variable and thereIf a function defines a local variable and there was a global variable with the same name, thewas a global variable with the same name, the function uses its local variable instead of usingfunction uses its local variable instead of using the global variablethe global variable
  • 46. Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }}
  • 47. Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 0 Global variables are automatically initialized to 0
  • 48. Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 0 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 1
  • 49. Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} 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 UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} 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 UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} 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 UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} 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 UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} 6
  • 54. Example of Defining and UsingExample of Defining and Using Global and Local VariablesGlobal and Local Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable Void fun();Void fun(); // function signature// function signature void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }} void fun()void fun() {{ int x = 10;int x = 10; // Local variable// Local variable cout << x << endl;cout << x << endl; }} x 4 void main()void main() {{ x = 4;x = 4; fun();fun(); cout << x << endl;cout << x << endl; }}7
  • 55. II. Using ParametersII. Using Parameters  Function Parameters come in threeFunction Parameters come in three flavors:flavors: Value parametersValue parameters – which copy the values of– which copy the values of the function argumentsthe function arguments Reference parametersReference parameters – which refer to the– which refer to the function arguments by other local names andfunction arguments by other local names and have the ability to change the values of thehave the ability to change the values of the referenced argumentsreferenced arguments Constant reference parametersConstant reference parameters – similar to– similar to the reference parameters but cannot changethe reference parameters but cannot change the values of the referenced argumentsthe values of the referenced arguments
  • 56. Value ParametersValue Parameters  This is what we use to declare in the function signature orThis is what we use to declare in the function signature or function header, e.g.function header, e.g. int max (int x, int y);int max (int x, int y);  Here, parameters x and y are value parametersHere, parameters x and y are value parameters  When you call the max function asWhen you call the max function as max(4, 7)max(4, 7), the values 4 and 7, the values 4 and 7 are copied to x and y respectivelyare copied to x and y respectively  When you call the max function asWhen you call the max function as max (a, b),max (a, b), where a=40 andwhere a=40 and b=10, the values 40 and 10 are copied to x and y respectivelyb=10, the values 40 and 10 are copied to x and y respectively  When you call the max function asWhen you call the max function as max( a+b, b/2),max( a+b, b/2), the values 50the values 50 and 5 are copies to x and y respectivelyand 5 are copies to x and y respectively  Once the value parameters accepted copies of theOnce the value parameters accepted copies of the corresponding arguments data, they act as localcorresponding arguments data, they act as local variables!variables!
  • 57. Example of Using ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ValueExample of Using Value Parameters and Global VariablesParameters and Global Variables #include <iostream.h>#include <iostream.h> int x;int x; // Global variable// Global variable void fun(int x)void fun(int x) {{ cout << x << endl;cout << x << endl; x=x+5;x=x+5; }} void main()void main() {{ x = 4;x = 4; fun(x/2+1);fun(x/2+1); cout << x << endl;cout << x << endl; }} 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 ParametersReference Parameters  As we saw in the last example, any changes inAs we saw in the last example, any changes in the value parameters don’t affect the originalthe value parameters don’t affect the original function argumentsfunction arguments  Sometimes, we want to change the values of theSometimes, we want to change the values of the original function arguments or return with moreoriginal function arguments or return with more than one value from the function, in this case wethan one value from the function, in this case we use reference parametersuse reference parameters  A reference parameter is just another name to theA reference parameter is just another name to the original argument variableoriginal argument variable  We define a reference parameter by adding the & inWe define a reference parameter by adding the & in front of the parameter name, e.g.front of the parameter name, e.g. double update (doubledouble update (double && x);x);
  • 64. Example of Reference ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4;int x = 4; // Local variable// Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersExample of Reference Parameters #include <iostream.h>#include <iostream.h> void fun(int &y)void fun(int &y) {{ cout << y << endl;cout << y << endl; y=y+5;y=y+5; }} void main()void main() {{ int x = 4; // Local variableint x = 4; // Local variable fun(x);fun(x); cout << x << endl;cout << x << endl; }} 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 ParametersConstant Reference Parameters  Constant reference parameters are used underConstant reference parameters are used under the following two conditions:the following two conditions:  The passed data are so big and you want to saveThe passed data are so big and you want to save time and computer memorytime and computer memory  The passed data will not be changed or updated inThe passed data will not be changed or updated in the function bodythe function body  For exampleFor example void report (void report (constconst stringstring && prompt);prompt);  The only valid arguments accepted by referenceThe only valid arguments accepted by reference parameters and constant reference parametersparameters and constant reference parameters are variable namesare variable names  It is a syntax error to pass constant values orIt is a syntax error to pass constant values or expressions to the (const) reference parametersexpressions to the (const) reference parameters