C++ Functions
Objectives
1. Be able to implement C++ functions
2. Be able to share data among functions
2
Objective 1: Implementing C++ functions
What is a function?Understand two difference function types
and their structures. How to implement each function?
3
Structure of Essay
4
Version 1
Version 2
One point for each paragraph
divide and conquer
Divide & Conquer in Software Development
We implement app to finish a task . The task is divided into smaller tasks Implementing each simple task by a function
5
divide
processingIncomeTaxes
getIncome computeTaxes printTaxes
conquer
Paragraph vs Function
Consists of one or more sentences,
Deals with one point Begins on a new
usually indented line
Consists of one or more statements
Deals with one smaller task
Begins with a function name
6
Function Types
StandardUser-defined
7
8
Standard Functions Build-in functions Organized in 100+libraries
<iostream> <cmath> <cctype>
How to use a build-in function?Where are librariesWhich function you want to useDoes the function need inputs
9
Standard Math Functions
#include <iostream>#include <cmath>
using namespace std;
int main() {// Getting a double valuedouble x;cout << "Please enter a real number: ";cin >> x;// Compute the ceiling and the floor of the real numbercout << "The ceil(" << x << ") = " << ceil(x) << endl;cout << "The floor(" << x << ") = " << floor(x) << endl;
}
http://isocpp.org/wiki/faq/coding-standards#std-headers
Hands-on Experience (1)
ceil(-2.5) =? floor(-2.5)=?Hint
Copy and paste code to https://ideone.com/ using new input (-2.5)
11
12
Standard Character Functions
#include <iostream> // input/output handling#include <cctype> // character type functions
using namespace std;
int main() {char ch;cout << "Enter a character: ";cin >> ch; cout << "The toupper(" << ch << ") = " << (char) toupper(ch) << endl;cout << "The tolower(" << ch << ") = " << (char) tolower(ch) << endl;if (isdigit(ch))
cout << "'" << ch <<"' is a digit!\n";else
cout << "'" << ch <<"' is NOT a digit!\n";}
Explicit casting
<ctype.h> vs cctype
Demo
http://ideone.com/lP7TxrAt least two test cases are required
Char is an alphabet (x)Char is a digit (5)
13
14
User-Defined Functions
Implement a function to determine if a triangle is
<cmath> library does not include a standard function
15
Define a Function?
Step #1 – Implement the function in .cpp Step #2 – publish the function in
before the main function of the programfor yourself
a header file (.h file) for you or other people reuse
Step #3 (if using header) – Use the functions in main.cpp
16
Syntactic Structure of a Function?
The function header
<return value> <name> (<parameter list>)
The function body enclosed between
{ }
17
Example of User-defined Function
double computeTax(double income) { if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes;}
18
double computeTax(double income){ if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes;}
Example of User-defined Function
Function header
Descriptive name
19
Example of User-defined Function
double computeTax(double income){ if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes;}
Function header
Function body
How to Improvement
double computeTax(double income){ if (income < 5000.0) return 0.0; double taxes = 0.07 * (income-5000.0); return taxes;}
20
double computeTax(double income) { const double baseIncome=5000.0; const double taxRates=0.07; double taxes =-1.0; if (income < baseIncome) { taxes=0.0; } else { taxes = taxRates * (income-baseIncome); } return taxes;}
Original version
Improved versionrefactoring
How to Improvement
21
double computeTax(double income, double baseIncome, double taxRates) { const double baseIncome=5000.0; const double taxRates=0.07; double taxes =-1.0; if (income < baseIncome) { taxes=0.0; } else { taxes = taxRates * (income-baseIncome); } return taxes;}
Improved version 2refactoring
double computeTax(double income) { const double baseIncome=5000.0; const double taxRates=0.07; double taxes =-1.0; if (income < baseIncome) { taxes=0.0; } else { taxes = taxRates * (income-baseIncome); } return taxes;}
Improved version
22
Function Header vs. Signature
Example
double computeTaxes(double) ;
Unnamed Parameter
Semicolon;
23
TaxesMain.cpp#include <iostream>
using namespace std;
// Function Signature double getIncome(string); double computeTaxes(double); void printTaxes(double);
int main() {
// Get the income;double income = getIncome("Please enter the employee income: ");
// Compute Taxesdouble taxes = computeTaxes(income);
// Print employee taxesprintTaxes(taxes);}
double computeTaxes(double income) { if (income<5000) return 0.0; return 0.07*(income-5000.0);}
double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income;}
void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl;}
1. Copy and paste code
2. Add signatures
3. Replacing the red statements with refactored code
4. Test your code
Solution: https://ideone.com/Y53Iwf
24
#include <iostream>
using namespace std;
// Function Signature // add signature here
int main() {
// Get the income;double income = getIncome("Please enter the employee income: ");
// Compute Taxesdouble taxes = computeTaxes(income);
// Print employee taxesprintTaxes(taxes);}
double computeTaxes(double income) { if (income<5000) return 0.0; return 0.07*(income-5000.0);}
double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income;}
void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl;}
Hands-on Experience (2)
25
Publish Your Functions
Build libraries to be used by you and your customers
Create header files to store function signatures
26
// This is a header file structure
#ifndef TAXESRULES_H_ // check if a unique value #define TAXESRULES_H_
TaxesRules.h
compiler directive
#include <iostream>#include <string>
other header files
#endif
//All functions signatures here
<FILE>_H_
//Never put functions implementation here
27
#ifndef TAXESRULES_H_ #define TAXESRULES_H_
TaxesRules.h
#include <iostream>#include <string>
using namespace std;
/** purpose -- to get the employee income input -- a string prompt to be displayed to the user output -- a double value representing the income */double getIncome(string);
// purpose -- to compute the taxes for a given income// input -- a double value representing the income// output -- a double value representing the taxesdouble computeTaxes(double);
void printTaxes(double);
#endif
28
TaxesRules.cpp
#include “TaxesRules.h"
double computeTaxes(double income) { // need to refactor later if (income<5000) return 0.0; return 0.07*(income-5000.0);}
double getIncome(string prompt) { cout << prompt; double income; cin >> income; return income;}
void printTaxes(double taxes) { cout << "The taxes is $" << taxes << endl;}
Main Program File
29
TaxesMain.cpp
#include “TaxesRules.h"
int main() {
// Get the income; double income = getIncome("Please enter the employee income: ");
// Compute Taxes double taxes = computeTaxes(income);
// Print employee taxes printTaxes(taxes);}
Files Needed for User-defined Functions
Head files TaxesRules.h
Implementation of the header files TaxesRules.cpp
One driver/Main file TaxesMain.cpp
30
31
Discussion: Why Do We Need Function Signature?
For Information Hiding Only publish function signatures in a header (.h) file Hide implementation details
For Function Abstraction We can change the implementation details from time
to time to Improve function performance make the customers focus on the purpose of the function,
not its implementation
Objective 2: Sharing data among functions
Global Variable (bad practice)
Passing parametersValue parametersReference parameters
32
Sharing Using Global Variables
33
http://ideone.com/L1ogIq
Global var
Using Global Variables
34
x 0
Using Global Variables
35
x 0
int main(){ f2(); cout << x << endl ;}
1
Using Global Variables
36
x 0
void main(){ f2(); cout << x << endl ;}
1
void f2(){ x += 4; f1();}
2
4
Using Global Variables
37
45x
void main(){ f2(); cout << x << endl ;}
1
void f2(){ x += 4; f1();}
3
void f1(){ x++;}
4
Using Global Variables
38
45x
void main(){ f2(); cout << x << endl;}
1
void f2(){ x += 4; f1();}
3
void f1(){ x++;}5
Using Global Variables
39
45x
void main(){ f2(); cout << x << endl;}
1
void f2(){ x += 4; f1();}6
Using Global Variables
40
45x
void main(){ f2(); cout << x << endl;}
7
Using Global Variables
41
45x
void main(){ f2(); cout << x << endl;}8
Using Global Variables
42
43
What is Bad About UsingGlobal Vairables?
Not safe! If two or more programmers are working together in a
program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value!
Against The Principle of Information Hiding! this gives all functions the freedom to change the
values stored in the global variables at any time
Example of Defining and Using Global and Local Variables
44
45
Example of Defining and Using Global and Local Variables
x 0
Global variables are automatically initialized to 0
46
Example of Defining and Using Global and Local Variables
x 0
int main() { x = 4; fun(); cout << x << endl;}
1
Example of Defining and Using Global and Local Variables
47
x 4
int main() { x = 4; fun(); cout << x << endl;}
2
void fun()
{ int x = 10; cout << x << endl;}
x ????
3
Example of Defining and Using Global and Local Variables
48
x 4
int main() { x = 4; fun(); cout << x << endl;}
2
void fun()
{ int x = 10; cout << x << endl;}
x 10
3
Example of Defining and Using Global and Local Variables
49
x 4
int main() { x = 4; fun(); cout << x << endl;}
2
void fun()
{ int x = 10; cout << x << endl;}
x 10
4
Example of Defining and Using Global and Local Variables
50
x 4
int main() { x = 4; fun(); cout << x << endl;}
2
void fun()
{ int x = 10; cout << x << endl;}
x 10
5
Example of Defining and Using Global and Local Variables
51
x 4
int main() { x = 4; fun(); cout << x << endl;}
6
Example of Defining and Using Global and Local Variables
52
x 4
int main() { x = 4; fun(); cout << x << endl;}7
53
Passing Value Parameters
Copy the values of the function call’s arguments to callee’s
Any changes in the callee’s value parameters don’t affect the original function arguments
Example of Using Value Parameters
54
x 0
int main() { x = 4; fun(x/2+1); cout << x << endl;}
1
Example of Using Value Parameters and Global Variables
55
x 4
void main(){ x = 4; fun(x/2+1); cout << x << endl;}
2
void fun(int x ){ cout << x << endl; x=x+5;}
3
3
Example of Using Value Parameters
56
x 4
Int main(){ x = 4; fun(x/2+1); cout << x << endl;}
2
void fun(int x ){ cout << x << endl; x=x+5;}
3
4
8
Example of Using Value Parameters
57
x 4
int main(){ x = 4; fun(x/2+1); cout << x << endl;}
2
void fun(int x ){ cout << x << endl; x=x+5;}
8
5
Example of Using Value Parameters
58
x 4
int main() { x = 4; fun(x/2+1); cout << x << endl;}
6
Example of Using Value Parameters
59
x 4
int main() { x = 4; fun(x/2+1); cout << x << endl;}7
60
Passing Reference Parameters Want to change the values of the original
function arguments
double update (double & x);
FFFF
FFFF
& ampersand
Example of Reference Parameters
61
int main(){ int x = 4; fun(x); cout << x << endl;}
1 x? x4
Example of Reference Parameters
62
int main(){ int x = 4; fun(x); cout << x << endl;}
2x? x4
void fun( int & y ){ cout<<y<<endl; y=y+5;}
3
Example of Reference Parameters
63
int main(){ int x = 4; fun(x); cout << x << endl;}
2x? x4
void fun( int & y ){ cout<<y<<endl; y=y+5;}
4 9
Example of Reference Parameters
64
int main(){ int x = 4; fun(x); cout << x << endl;}
2x? x9
void fun( int & y ){ cout<<y<<endl; y=y+5;}5
Example of Reference Parameters
65
int main(){ int x = 4; fun(x); cout << x << endl;}
6
x? x9
Example of Reference Parameters
66
int main(){ int x = 4; fun(x); cout << x << endl;}
x? x9
7
Hands-on Experience (3)
67
https://ideone.com/n0luWe
Summary
Declare and Implementing C++ functions for reusing
Passing by valuePassing by reference
68
69
Function Overloading
defined more than once different data types or
different number of parameters
Hands-on Experience (4)
Add statementmax(3.5, 2)
How to fix it?
Modify the code at http://ideone.com/6iZRVM
70