chapter six -seven discover how to use them in a program … · predefined & user -defined...
TRANSCRIPT
Cukurova University Electrical-
Electronics Engineering Dept.
Assisstant Prof. Dr. Turgay ĐBRĐKÇĐ
Thursday, November 25, 2010
Chapter SixChapter Six--SevenSeven
PREDEFINED & USERPREDEFINED & USER--DEFINED DEFINED
FUNCTIONS FUNCTIONS
ObjectivesObjectives
In these chapters you will:
Learn about standard (predefined) functions and
discover how to use them in a program
Learn about user-defined functions
Examine value-returning functions, including
actual and formal parameters
Explore how to construct and use a value-
returning, user-defined function in a program
22 EEE117 Computer Programming
FunctionsFunctions
Functions are like building blocks
They allow complicated programs to be divided into manageable pieces
are often referred to as modules
are like miniature programs
can be put together to form a larger program
33 EEE117 Computer Programming
Advantages of Using FunctionsAdvantages of Using Functions
1. To help make the program more understandable
2. To modularize the tasks of the program
• building blocks of the program
3. Write a module once
• those lines of source code are called multiple times
in the program
44 EEE117 Computer Programming
Advantages of Using FunctionsAdvantages of Using Functions
4. While working on one function, you can
focus on just that part of the program
• construct it,
• debug it,
• perfect it.
5. Different people can work on different
functions simultaneously.
6. If a function is needed in more than one place
in a program, or in different programs, you
can write it once and use it many times
55 EEE117 Computer Programming
Standard FunctionsStandard Functions
In college algebra a function is defined as a rule or correspondence between values, called the function’s arguments, and the unique value of the function associated with the arguments
If f(x) = 2x + 5, then f(1) = 7, f(2) = 9, and f(3) = 11
1, 2, and 3 are arguments
7, 9, and 11 are the corresponding values
66 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Standard FunctionsStandard Functions
Some of the predefined mathematical functions are:
• sqrt(x)
• pow(x,y)
• floor(x)
Predefined functions are organized into separate libraries
I/O functions are contained in the header file iostream
Math functions are contained in the header file cmath
77 EEE117 Computer Programming
The Power Function (pow)The Power Function (pow)
pow(x,y) calculates xy, for example:
pow(2,3) = 8.0
Is of the type double or the function pow
returns a value of the type double
x and y are called the parameters (or
arguments) of the function pow
Function pow has two parameters
88 EEE117 Computer Programming
The sqrt and floor FunctionsThe sqrt and floor Functions
The square root function sqrt(x)
• calculates the non-negative square root of x for x >= 0.0
• sqrt(2.25) is 1.5
• It is of the type double and has only one parameter
The floor function floor(x)
• calculates the largest whole number not greater than x
• floor(48.79) is 48.0
• It is of the type double and has only one parameter
99 EEE117 Computer Programming 1010 EEE117 Computer Programming
UserUser--Defined FunctionsDefined Functions
The first four properties form the heading of the function
The fifth property is called the body of the function
These properties form the function definition
For predefined functions, we only need to be concerned with the first four properties
Formal Parameter - A variable declared in the function heading
Actual Parameter - A variable or expression listed in a call to a function
1111 EEE117 Computer Programming
SyntaxSyntax
The syntax of the formal parameter list is:
dataType identifier, dataType identifier, ...
The syntax for a function call is:
functionName(actual parameter list)
The syntax for the actual parameter list is:
expression or variable,expression or variable, ...
1212 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
FunctionsFunctions
The formal parameter list can be empty
If the formal parameter list is empty
• the parentheses are still needed
• the function heading of the value-returning function takes either of the following forms:
- functionType functionName()
- functionType functionName(void)
• in a function call the actual parameter is empty
A call to a value-returning function with an empty formal parameter list is: functionName()
1313 EEE117 Computer Programming
Function PrototypeFunction Prototype
Function Prototype - function heading without the
body of the function
The syntax is:
functionType functionName(parameter list);
It is not necessary to specify the variable name in the
parameter list
The data type of each parameter must be specified
1414 EEE117 Computer Programming
UserUser--Defined FunctionsDefined Functions
Void functions - functions that do not have a data type
Value-returning functions - functions that have a data type
To use these functions you need to:
• include the correct header file
• know the name of the function
• know the number of parameters, if any
• know the data type of each parameter
• know the data type of the value computed by the function, called the type of the function
1515 EEE117 Computer Programming
UserUser--Defined FunctionsDefined Functions
Since the value returned by a value-returning function is
unique, we:
• save the value for further calculation
• use the value in some calculation
• print the value
A value-returning function is either used in an assignment
statement or in an output statement such as cout
There is one more thing that is associated with a function:
• the code that is required to accomplish the task
1616 EEE117 Computer Programming
ValueValue--Returning FunctionsReturning Functions
To call a value-returning function:
• Use its name, with the actual parameters (if any) in parentheses
• There is a one-to-one correspondence between actual and formal parameters
A value-returning function is called in an expression
The expression may be part of an assignment statement or an output statement
A function call in a program results in the execution of the body of the called function
1717 EEE117 Computer Programming
ValueValue--returning Functionsreturning Functions
The syntax is:
functionType functionName(formal parameter list)
{
statements
}
functionType - type of the value returned by the function
functionType - also called the data type of the value-returning function
1818 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
The return StatementThe return Statement
Once the function computes the value, the function returns this value via the return statement
The syntax of the return statement is:
return expression or variable;
When a return statement executes in a function, the function immediately terminates and the control goes back to the caller
When a return statement executes in the function main, the program terminates
1919 EEE117 Computer Programming
Void FunctionsVoid Functions
Void functions do not return a value
• Think of them as performing a task
They may or may not have parameters
They usually do not have a return statement
• Although a return can be used to exit a
function
2020 EEE117 Computer Programming
Void Functions Void Functions WithoutWithout ParametersParameters
Syntax for the declaration:
void functionName (void)
{
statements
}
Syntax for the call:
functionName();
voidvoid in the parameter
list is optional
The parentheses in the call is required, even when there
are no parameters
2121 EEE117 Computer Programming
Void Functions Void Functions WithoutWithout ParametersParameters
Consider a program which will print the following pattern:
******************************
******************************
*********** Hello ***********
******************************
******************************
******* EEE-117 STUDENTS *****
******************************
******************************
Note
• The prototype
• The syntax of the declaration, the definition
• The syntax of the call
2222 EEE117 Computer Programming
Improving FunctionsImproving Functions
We need to communicate to
the functionsWe need to communicate to
the functions
2323 EEE117 Computer Programming
Improving FunctionsImproving Functions
Sending values to the functions
with value parameters.Sending values to the functions
with value parameters.
2424 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Functions Functions WithWith ParametersParameters
Make functions more versatile
Send to the function a value
• tells it how many times to do something
• gives it a value to be used in some way
(printed, calculated, etc.)
2525 EEE117 Computer Programming
Function ParametersFunction Parameters
Formal parameter
• declared in the function heading
Actual parameter
• variable or expression listed in a call
(invocation) of the function
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}2626 EEE117 Computer Programming
Function Call (Invocation)Function Call (Invocation)
Use the name of the function as if it is a
statement
When the program reaches that statement,
Control is then transferred to the function
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
2727 EEE117 Computer Programming
Function DeclarationsFunction Declarations
Why the prototypes?
All identifiers (including function names) must be
declared before they are used
Compiler must know about the function
void calculate_rates ( );
void find_matching_records (char id[]);
void main ( )
{ . . .
calculate_rates ( );
find_matching_records (emp_id);
void calculate_rates ( );
void find_matching_records (char id[]);
void main ( )
{ . . .
calculate_rates ( );
find_matching_records (emp_id);
ParametersParameters
Function nameFunction nameFunction typeFunction type
2828 EEE117 Computer Programming
Function DeclarationsFunction Declarations
It is also legal to include the definition (body) of
the function with the heading all before main( )
void print_summary (int total)
{ . . .
cout << . . .
}
void main ( )
{ . . .
print_summary (rpt_total);
revenue = rpt_total * .72675;
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
void main ( )
{ . . .
print_summary (rpt_total);
revenue = rpt_total * .72675;
. . .
}
This takes care of informing the
compiler of what it needs
and defining the source code also
This takes care of informing the
compiler of what it needs
and defining the source code also
2929 EEE117 Computer Programming
Syntax of the Parameter ListSyntax of the Parameter List
In parentheses
For each parameter
• specify type then name
• separate type-name pairs with commas
void print_max_value
(int value_1, int value_2, int value_3)
{
. . .
}
void print_max_value
(int value_1, int value_2, int value_3)
{
. . .
}
3030 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Value ParametersValue Parameters
Defn => a formal parameter that receives a
copy of the contents of the corresponding
actual parameter
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
void main ( )
{ . . .
print_summary (rpt_total);
. . .
}
void print_summary (int total)
{ . . .
cout << . . .
}
17
3131 EEE117 Computer Programming
Value ParameterValue Parameter
Acts much like an assignment of a value to a
variable
The formal parameter is considered local to the
function
The actual parameter
may be an
expression
or a constant
void main ( )
{ print_summary (0.5*rpt_total);
. . .
print_summary (200);
}
void print_summary (int total)
{ . . .
cout << . . .
}
View example program
3232 EEE117 Computer Programming
Value ParametersValue Parameters
Consider … When we change the contents of
the value parameter in the function …
• What (if anything) happens to the actual
parameter?
No, nothing happens.The actual parameter remains unchanged
No, nothing happens.The actual parameter remains unchanged
3333 EEE117 Computer Programming
Reference ParametersReference Parameters
What if we wanted the actual parameter to
change?
C++ allows us to do this with reference
parameters.
What is different in thisversion of the function?
What is different in thisversion of the function?
3434 EEE117 Computer Programming
Reference ParametersReference Parameters
It would be helpful to
be able to have the functions
communicate back to the
calling module.
It would be helpful to
be able to have the functions
communicate back to the
calling module.
3535 EEE117 Computer Programming
Reference ParametersReference Parameters
Reference Parameters provide
that capabilityReference Parameters provide
that capability
3636 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Reference ParametersReference Parameters
Use the ampersand & between the parameter
type and the identifier
What actually happens is that this causes the
address of the actual parameter to be sent to the
formal parameter
Then anything that happens to the formal
parameter is happening to the actual
parameter
3737 EEE117 Computer Programming
Contrast Value & Reference ParametersContrast Value & Reference Parameters
Receives copy of value
Actual parameter can be
constant, variable, expression
Value travels one way only
(in)
Exact match of types (formal
& actual) not critical
Receives address of actual
parameter
Actual parameter must be a
variable
Value can be thought of as
traveling both ways (in and
out)
Formal & actual parameters
must be of same type
ValueValue ReferenceReference
3838 EEE117 Computer Programming
Reference ParametersReference Parameters
5 10
5
Recall our previous model for a function with value
parameters
(values go in only)
Now consider a new version for reference
parameters
Values go both
in & out
3939 EEE117 Computer Programming
Value and Reference Parameters and Value and Reference Parameters and Memory AllocationMemory Allocation
• When a function is called,
•Memory for its formal parameters and local
variables is allocated in the function data
area.
• In the case of a value parameter,
•The value of the actual parameter is copied
into the memory cell of its corresponding
formal parameter.
4040 EEE117 Computer Programming
Value and Reference Parameters and Value and Reference Parameters and Memory AllocationMemory Allocation
• In the case of a reference parameter,
• The address of the actual parameter passes to the formal
parameter.
• Content of the formal parameter is an address.
• During execution,
• changes made to the formal parameter change the value of
the actual parameter.
• Stream variables (for example, ifstream and
ofstream) should be passed by reference
4141 EEE117 Computer Programming
Value and Reference Parameters and Value and Reference Parameters and Memory AllocationMemory Allocation
Note Example Program 7-6
Before function is called, this is the memory picture
4242 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Value and Reference Parameters and Value and Reference Parameters and Memory AllocationMemory Allocation
Once the flow of control is inside function funOne(
), this is the memory picture:
Changes made to parameter bb will affect
num2num2 in main
4343 EEE117 Computer Programming
Value and Reference Parameters and Value and Reference Parameters and Memory AllocationMemory Allocation
Likewise, for function funTwo( )
• Changes made to x and w will affect num2
and ch, respectively
Remember, this is because reference parameters hold addresses of the
actual parameters
4444 EEE117 Computer Programming
Scope of IdentifiersScope of Identifiers
Scope <=> the region of program code where it is
legal to reference (use) an identifier
Local scope <=> from where an identifier is
declared, on to the end of the block
void print_max_value
(int value_1, int value_2, int value_3)
{ int hold_value;
hold_value = value_1;
if (value_2 > hold_value)
hold_value = value_2;
. . .
}
void print_max_value
(int value_1, int value_2, int value_3)
{ int hold_value;
hold_value = value_1;
if (value_2 > hold_value)
hold_value = value_2;
. . .
}
BlockBlock
4545 EEE117 Computer Programming
Scope of IdentifiersScope of Identifiers
Global (or file) scope
• declared outside a block
• from point of declaration on to end of entire
file
int sum, count, n1, n2;
void print_totals( int amt);
void main ( )
{ . . .
int sum, count, n1, n2;
void print_totals( int amt);
void main ( )
{ . . .
Rest of fileRest of file
4646 EEE117 Computer Programming
Name PrecedenceName Precedence
Name of a local identifier can be the same as the
name of a global identifier
Name precedence <=> local identifier has
precedence over
global identifier
with same namevoid print_sum (int n1, int n2)
{ int sum;
sum = n1 + n2;
cout << sum; }
void main( )
{ float sum, x, y;
. . .
print_sum (x, 34);
. . .
void print_sum (int n1, int n2)
{ int sum;
sum = n1 + n2;
cout << sum; }
void main( )
{ float sum, x, y;
. . .
print_sum (x, 34);
. . .4747 EEE117 Computer Programming
Scope RulesScope Rules
How to decide where an identifier is accessible
Look at where it is declared
• local (within a block)
• global (within the file)
• non-local (outside a given block)
Non local identifier may or may not be
accessible
4848 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
NonNon--Local Accessible When ...Local Accessible When ...
It is global and not same name as a local
identifier
The location in question is nested within
another block where the non local is declaredint x, y, z;
void do_it (float x)
{ char y; . . . }
void main ( )
{ float y, z;
. . . }
z
x
4949 EEE117 Computer Programming
Scope RulesScope Rules
Function names are global
• no such thing as nested functions
Formal parameters considered local to the
function
Global identifiers have scope
• from definition
• until end of file
Local identifiers with same name as non-local …
local take precedence
5050 EEE117 Computer Programming
Side EffectsSide Effects
Any effect of one function on another that is
• not part of the explicitly defined interface
between them
Caused by
• careless use of reference parameters
• poor design by use of global in functions
5151 EEE117 Computer Programming
Globals in FunctionsGlobals in Functions
Assign value to global
Call function
Use globals
in function
Note -- accordingto the instructorthis is generallya bad practice!
5252 EEE117 Computer Programming
Global in FunctionsGlobal in Functions
This is a tempting way to go
• especially when you don’t comprehend
parameters too well!!
But it can cause unexpected problems
• Two different functions can use the same
global (inadvertently)
• All of a sudden get strange results
Side
Effects
5353 EEE117 Computer Programming
Global ConstantsGlobal Constants
Value of a constant cannot be changed
Thus, acceptable to reference named constants
globally
• change of the constant can be done in the
source code -- then recompile
• that change is then done for all instances of
the identifier
const int lines_per_page = 66;
void main ( )
{ . . .
5454 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Lifetime of a VariableLifetime of a Variable
Defn => Period of time during program
execution when an identifier actually has
memory allocated to it
Variables local to
a function not
allocated space
until the program
enters the
function
void print_sum (int n1, int n2)
{ int sum;
sum = n1 + n2;
cout << sum; }
void main( )
{ float sum, x, y;
. . .
print_sum (24, 34);
void print_sum (int n1, int n2)
{ int sum;
sum = n1 + n2;
cout << sum; }
void main( )
{ float sum, x, y;
. . .
print_sum (24, 34);
De-allocated
when function
finishes
De-allocated
when function
finishes
5555 EEE117 Computer Programming
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5
y : 17GlobalsGlobals
LocalsLocals
Memory
5656 EEE117 Computer Programming
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5
y : 17GlobalsGlobals
a: 0
LocalsLocals
a allocated
Memory
5757 EEE117 Computer Programming
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5
y : 17GlobalsGlobals
LocalsLocals
a de-allocated
Memory
5858 EEE117 Computer Programming
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5
y : 17GlobalsGlobals
LocalsLocals
b : 2
b allocated
Memory
5959 EEE117 Computer Programming
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
int x=5, y;
void do_it( )
{ int a = 0;
. . . }
void to_it (float b )
{ b = 3 ; . . . }
void main ( )
{ y = 17;
do_it ( );
to_it ( );
cout << x + y;
}
Lifetime of a VariableLifetime of a Variable
O.S.
.exe code
x: 5
y : 17GlobalsGlobals
LocalsLocals
b de-allocated
6060 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Lifetime of a VariableLifetime of a Variable
Scope is a compile-time issue
Lifetime is a run-time issue
Automatic variable
• allocated at block entry
• deallocated at exit
Static variable
• once allocated remains allocated for whole program
6161 EEE117 Computer Programming
Automatic vs. Static VariableAutomatic vs. Static Variable
storage for
automatic variable
is allocated at block
entry and
deallocated at block
exit
storage for static
variable remains
allocated throughout
execution of the
entire program
6262 EEE117 Computer Programming
Static VariablesStatic Variables
By default, local variables are automatic.
To obtain a static local variable, you must use the reserved work static in its declaration.
6363 EEE117 Computer Programming
StaticStatic and and AutomaticAutomatic Local VariablesLocal Variables
int popularSquare( int n)
{
static int timesCalled = 0 ; // initialized
// only once
int result = n * n ;
// initialized each time
timesCalled = timesCalled + 1 ;
cout << “Call # “ << timesCalled << endl ;
return result ;
}
int popularSquare( int n)
{
static int timesCalled = 0 ; // initialized
// only once
int result = n * n ;
// initialized each time
timesCalled = timesCalled + 1 ;
cout << “Call # “ << timesCalled << endl ;
return result ;
}
6464 EEE117 Computer Programming
Static & Automatic VariablesStatic & Automatic Variables
What gets printed?What gets printed?
6565 EEE117 Computer Programming
Function OverloadingFunction Overloading
In C++, you can have several functions with the
same name.
The compiler will consider them different if:
• The number and/or type of parameters is
different and/or the type of the value
returned is different
• This is called the "signature" of a function
• C++ calls this overloading a function name.
6666 EEE117 Computer Programming
Cukurova University Electrical-
Electronics Engineering Dept.
Function OverloadingFunction Overloading
Instead of:
int largerInt(int x, int y);
char largerChar(char first, char second);
double largerDouble(double u, double v);
string largerString(string first, string second);
It is possible to overload a single function name
int larger(int x, int y);
char larger(char first, char second);
double larger(double u, double v);
string larger(string first, string second);
6767 EEE117 Computer Programming
Functions with Default ParametersFunctions with Default Parameters
Normally when a function is called,
• The number of actual and formal parameters must be the
same.
• C++ relaxes this condition for functions with default
parameters.
Default value for a parameter specified when the
function name appears for the first time
• In the prototype
• Or if whole definition appear before main()
6868 EEE117 Computer Programming
Functions with Default ParametersFunctions with Default Parameters
Example:
void doSomething (int x = 0, float y = 1.5);
Then the function can be called three different ways:
doSomething(6,12.99); // default values overridden
doSomething(4); // default int overridden
// default float of 1.5 is used
doSomething(); // both default values are used
6969 EEE117 Computer Programming 7070 EEE117 Computer Programming