Transcript CIS162AB

CIS162AB - C++
Functions
Juan Marquez
04_functions.ppt
Overview of Topics
•
•
•
•
•
Top-Down Design
Structure Charts
Predefined Functions
Black Box Analogy
Programmer Defined Functions
– Function Prototype, Function Call, Function Definition
• Variable Scope
– Local vs Global
• Function Overloading
CIS162AB
2
Top-Down Design
• A method where the major task to be
accomplished is divided into subtasks.
– Major Task: clean house
– Subtasks: dust , vacuum, sweep, mop
– Major Task: P03 ex Calculate Total Order
– Subtasks: get price, get quantity,
calculate costs, display order
CIS162AB
3
Subtasks
• Each subtask may produce some result.
• Treat them as small programs.
Input -> Process -> Output
• These subtasks can be used at different
times in one program or placed in a library
and used by many different programs.
• cout is a complicated task that displays
information to the console, and is used by
many different programs.
CIS162AB
4
Structure Chart
• Top-Down design is depicted with a structure chart.
CIS162AB
5
Structure Charts
• A structure chart is a design tool that shows the
overall structure of a program, but omits specific
logic.
• Structure charts are developed at a much higher
level than flowcharts, because they only show
what tasks need to be completed, and not how they
will be completed.
• Flowcharts depict the detail steps of how a task
will be completed.
• The main benefit is in the initial planning of a
program.
CIS162AB
6
Implemented Using Functions
• Top-Down design is implemented using functions.
• A function is a collection of statements that are
grouped together to perform a specific operation.
• Before coding some programmer defined
functions, let’s look at some predefined
functions.
• It will help understand what we are trying to
develop if we look at how functions are used.
CIS162AB
7
Predefined Functions
• Square root function is named sqrt.
• The documentation for sqrt states the function
name, the type of the value that will be returned,
and the type and number of parameters.
double
sqrt(double);
returnType functionName (parameters);
• sqrt takes one parameter of the type double.
• The function is called using the following syntax:
answer = sqrt(num1);
CIS162AB
8
sqrt Example
#include <cmath>
using namespace std;
double num, answer;
cout << “Enter a number: “;
cin >> num;
answer = sqrt(num);
cout << “The square root of “ << num
<< “ is “ << answer;
CIS162AB
9
Function Call
• We issue a function call when we use a function.
• Processing control is passed to the function until it
completes its task and returns control back to the
calling function.
• Values are passed to functions as arguments.
• The words parameter and argument are closely
related. Parameter is used with function definitions,
and argument is used with function calls.
• Many functions return a value back,
but only one value can be returned.
CIS162AB
10
Power Function
• Functions can only return one value, but may have
many parameters.
answer = pow (num1, num2);
• Raises num1 to the power of num2.
In math it would be stated as:
answer = num1 num2
answer = pow(10.0, 2.0);
answer would be equal to 100.00 (10 2 )
CIS162AB
11
Small Programs
• Think of each function as a small program with
input, process, and output steps.
answer
= sqrt(num1);
returnType = functionName (arguments);
Output <
Process
< Input
• An IPO chart and Flowchart can be developed for
each function.
CIS162AB
12
Compiler Directives
• Predefined functions are stored in header files.
• Must be #included by programs using them,
or compiler will give syntax error stating function is
undeclared.
#include <cmath>
#include <cstdlib>
using namespace std;
CIS162AB
//sqrt,pow
//abs,labs
13
Additional Examples
• See textbook for additional examples of
predefined functions.
• Gives library or header file, function name,
return type, and parameter types.
CIS162AB
14
Type Casting
• Allows us to convert the value in a variable to a
desired data type.
• sqrt requires a parameter of type double.
• If you only have int type variables, you can type
cast for the function call:
answer = sqrt(double (intNum1));
• Actual value and data type of intNum1 is not
affected.
• This is very subtle and can be difficult to find a
bug or to maintain. Use type casting sparingly.
CIS162AB
15
New Type Casting Syntax
• static_cast<Type>(expression)
• This command takes expression and returns an
equivalent value in the data type specified in
Type.
• answer = sqrt(static_cast<double>(intNum1));
CIS162AB
16
3 Additional Type Casters
• const_cast<Type>(expression)
• dynamic_cast<Type>(expression)
• reinterpret_cast<Type>(expression)
• These have specific purposes and they are
not covered in this course .
CIS162AB
17
Black Box Analogy
• Many functions are designed as black boxes.
• We should not be concerned how the function
performs its processing. We only need to know the
inputs, outputs, and what it does.
• This is also known as Method Abstraction.
• double sqrt(double)
We know what is required to use it, but we don’t
know how it calculates the square root.
• Develop your own functions with the Black Box
Analogy in mind.
CIS162AB
18
Programmer Defined Functions
Three Components
1. Function Prototype
2. Function Call
3. Function Definition
CIS162AB
19
Function Prototype
• Before main() to make them global declarations
Data type of Function List of formal parameters
return value Name
with data types
double calcGross(int hours, double rate);
//note semicolon
CIS162AB
20
Function Call
void main()
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
}
In the function call the variables listed in the parentheses
are called arguments, and in the prototype they are call
formal parameters.
CIS162AB
21
Function Definition
• After main()
double calcGross(int hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
22
Three Parts to Function Definition
Header: double calcGross(int hours, double rate)
{
Body:
double gross;
gross = hours * rate;
Return:
return gross;
}
No semicolon after header.
CIS162AB
23
Function Definition Details
• No semicolon after closing parenthesis on
header.
• Variables used by function must be declared
locally.
• Variables listed in header are actually declared
as local variables.
• Statement with function call transfers control to
the function being called.
CIS162AB
24
Return Statement
• Only one value can be returned through return
statement.
• The data type of the variable used in the return
statement must match the return type specified in
header.
• Return statement returns the value back to the
variable listed to the left of the call statement.
• Return statement returns control back to the
calling function.
CIS162AB
25
Function Definitions and Prototypes
• Function Prototypes are actually NOT
required.
• Function Definitions may be placed anywhere
before being called, so placing definition
before main would eliminate prototypes.
• But doing this will not work when we get to
separate compilations.
• It’s best to form a good habit now, so you
don’t have to break a bad habit later.
CIS162AB
26
All Together Now
double calcGross(int hours, double rate); //prototype
void main()
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
//function call
}
double calcGross(int hours, double rate)
//definition
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
27
Single Return Statement
double calcGross(int hours, double rate)
{
double gross;
if (hours > 40)
gross = (40 * rate) + ((hours – 40) * rate * 1.5);
else
gross = hours * rate;
return gross;
}
CIS162AB
28
Multiple Return Statements
double calcGross(int hours, double rate)
{
if (hours > 40)
return ( (40 * rate) + ((hours – 40) * rate * 1.5));
else
return (hours * rate);
}
//In structured programming we usually want one way in,
and one way out of a function, so a single return
statement is preferred.
CIS162AB
29
Variable Scope
• Variable scope – determines in which function
or block of code a particular variable exists in.
• Let’s look at each the following topics in detail:
–
–
–
–
Local variables
Call-by-value
Block of code
Global variables
CIS162AB
30
Local Variables
• Variables are local to the function in which they are
defined.
• Variables defined in main() are assigned their own
memory and can only be referenced in main().
• Variables defined in calcGross() are assigned their
own memory and can only be referenced in
calcGross().
• These two functions cannot see or reference each
others variables
• They have separate memory allocations even though
the variable names may be the same.
CIS162AB
31
Memory and Call-by-Value
double calcGross(int hours, double rate); //parameters defined
as call-by-value
void main()
parameters.
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
}
double calcGross(int hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
32
Declare Variables and Functions
Function
Address
Variable
Value
main
1010
1020
1030
1040
1050
1060
hours
rate
pay
hours
rate
gross
?
?
?
?
?
?
calcGross
Values unknown after declaration.
CIS162AB
33
cin >> hours >> rate;
Function
Address
Variable
Value
main
1010
1020
1030
1040
1050
1060
hours
rate
pay
hours
rate
gross
40
10.00
?
?
?
?
calcGross
CIS162AB
34
pay = calcGross(hours,rate);
Function
Address
Variable
Value
main
1010
1020
1030
1040
1050
1060
hours
rate
pay
hours
rate
gross
40
10.00
?
40
10.00
?
calcGross
Call-by-Value - Values in variables of main are sent
to variables of calcGross.
CIS162AB
35
Control Transferred to calcGross
double calcGross(int hours, double rate);
void main()
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
//function call
}
double calcGross(int hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
36
gross = hours * rate;
Function
Address
Variable
Value
main
1010
1020
1030
1040
1050
1060
hours
rate
pay
hours
rate
gross
40
10.00
?
40
10.00
400.00
calcGross
CIS162AB
37
Return Value and Control to main
double calcGross(int hours, double rate);
void main()
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
}
double calcGross(int hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
38
return gross;
pay = calcGross(hours,rate);
Function
Address
Variable
Value
main
1010
1020
1030
1040
1050
1060
hours
rate
pay
hours
rate
gross
40
10.00
400.00
40
10.00
400.00
calcGross
Return sends the value to variable on the left side of the equal
sign
on the function call statement.
CIS162AB
39
Block of Code
• Block – contains single or multiple
statements (compound) and is defined with
an open and close brace {}.
• The variables declared in a block are local
to the block.
• Examples of blocks
–
–
–
–
Function block
Loop block
If statement block
Anywhere open and close braces are used.
CIS162AB
40
Two Blocks of Code
double calcGross(int hours, double rate);
void main()
{
int hours; double rate, pay;
cin >> hours >> rate;
pay = calcGross(hours,rate);
cout << pay;
}
double calcGross(int hours, double rate)
{
double gross;
gross = hours * rate;
return gross;
}
CIS162AB
41
Global Variables
• Global variables are defined before main
and they can be referenced by all the
functions in the program.
• Good use is for constants that store rates, or
a company name.
(FICA_RATE, OVERTIME_RATE,
COMPANY_NAME, etc.)
• A value that is the same in many different
programs.
CIS162AB
42
Global Variable No-no
• Do not make variables whose values change
during the execution of the program global
variables.
• It may seem easier to use global variables,
but it will actually lead to bad programming
practices and cause you problems as we
begin developing programs using functions
and separate compilations.
CIS162AB
43
Global Example
double calcGross(int hours, double rate);
const double OVERTIME_RATE = 1.5;
void main()
{
int hours; double rate, pay;
… // more statements here
cout << overtime << “ at “ << OVERTIME_RATE;
}
double calcGross(int hours, double rate)
{
if (hours > 40)
return ( (40 * rate)
+ ((hours – 40) * rate * OVERTIME_RATE));
else
return (hours * rate);
CIS162AB
44
}
Function Overloading
• Same function name but different parameter types
or number of parameters.
• Function name along with parameter profile is
referred to as the function signature.
• Functions cannot be overloaded based on different
modifiers or return type.
• Function overloading is a form of polymorphism.
• Polymorphism – Greek – many forms
CIS162AB
45
Function Overloading Example
double calcCost(
double price, int quantity)
double calcCost(
double price, double quantity)
{
{
double subtotal;
subtotal = quantity * price;
return (subtotal);
double subtotal;
subtotal = quantity * price;
return (subtotal);
}
}
//signature
//signature
//calcCost( double, int);
CIS162AB
//calcCost( double, double);
46
Summary
•
•
•
•
•
•
•
•
Top-Down Design
Black Box Analogy
Function Prototype
Function Call
Function Definition
Call-by-value
Variable Scope
Function Overloading
CIS162AB
47