Sei sulla pagina 1di 52

User Defined Functions

Chapter 7

Chapter Topics
Void Functions Without Parameters
Void Functions With Parameters
Reference Parameters
Value and Reference Parameters and Memory
Allocation
Reference Parameters and Value-Returning
Functions
Scope of an Identifier
Side Effects of Global Variables
Static and Automatic Variables
Function Overloading
Functions with Default Parameters

Void 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

Void Functions Without Parameters


Syntax for the declaration:
void functionName (void)
{
statements
void in the parameter
}
list is optional

Syntax for the call:


functionName();

The parentheses in the call


is required, even when there
are no parameters

Void Functions Without Parameters


Consider a program which will print the following
pattern:
******************************
******************************
********* Go Team ***********
******************************
******************************
********* BEAT ETBU **********
******************************
******************************

Note
The prototype
The syntax of the declaration, the definition
The syntax of the call

Improving Functions

We
Weneed
needto
tocommunicate
communicateto
to
the
thefunctions
functions

Improving Functions

Sending
Sendingvalues
valuesto
tothe
thefunctions
functions
with
withvalue
valueparameters.
parameters.

Functions With Parameters


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.)

Function 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 << . . .
}

Function Call (Invocation)


Use the name of the function as if it is a
statement
void
{

main ( )
. . .
print_summary (rpt_total);
. . .

}
void print_summary (int total)
{ . . .
cout << . . .
}

When the program reaches that statement,


Control is then transferred to the function

10

Function Declarations

11

Why the prototypes?


All identifiers (including function names) must be
declared before they are used
void calculate_rates ( );
void find_matching_records (char id[]);
Parameters
void main ( )
{
. . .
calculate_rates ( );
find_matching_records (emp_id);

Compiler
must know about the function
Function
type
Function name

Function Declarations

12

It is also legal to include the definition


(body) of the function with the heading all
before main( )
void
void
{{
}}
void
void
{{

}}

print_summary
print_summary (int
(int total)
total)
.. .. ..
cout
cout <<
<< .. .. ..
This
Thistakes
takescare
careof
of informing
informingthe
the

compiler
compiler of
ofwhat
whatititneeds
needs
and
anddefining
definingthe
thesource
sourcecode
codealso
also

main
main (( ))
.. .. ..
print_summary
print_summary (rpt_total);
(rpt_total);
revenue
revenue == rpt_total
rpt_total ** .72675;
.72675;
.. .. ..

Syntax 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)
{
. . .
}

13

Value Parameters

14

Defn => a formal parameter that receives a


copy of the contents of the corresponding
actual parameter
17
void
{

main ( )
. . .
print_summary (rpt_total);
. . .

}
void print_summary (int total)
{ . . .
cout << . . .
}

Value Parameter

15

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
void main ( )
expression
{ print_summary (0.5*rpt_total);
. . .
or a constant
print_summary (200);

Viewexample
program

}
void print_summary (int total)
{ . . .
cout << . . .
}

Value Parameters

16

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

Reference Parameters

17

What if we wanted the actual parameter to


change?
C++ allows us to do this with reference
parameters.

What is different in this


version of the function?

Reference Parameters

ItItwould
wouldbe
behelpful
helpfulto
to
be
beable
ableto
tohave
havethe
thefunctions
functions
communicate
communicateback
backto
tothe
the
calling
callingmodule.
module.

18

Reference Parameters

Reference
ReferenceParameters
Parametersprovide
provide
that
thatcapability
capability

19

Reference Parameters

20

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

Viewexample
program

Contrast Value & Reference Parameters


Value
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

21

Reference
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

Reference Parameters
Recall our previous model for a function with
value parameters
5
(values go in only)

Now consider a new version for reference


parameters
10
5
Values go both
in & out

22

Value and Reference Parameters


and Memory 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.

23

Value and Reference Parameters


and Memory Allocation

24

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

Value and Reference Parameters


and Memory Allocation
Note Example Program 7-6
Before function is called, this is the
memory picture

25

Value and Reference Parameters


and Memory Allocation
Once the flow of control is inside function
funOne( ), this is the memory picture:

Changes made to
parameter b will affect
num2 in main

26

Value and Reference Parameters


and Memory 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

27

28

Scope 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

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;
. . .
}

Scope of Identifiers

29

Global (or file) scope


declared outside a block
from point of declaration on to end of entire file

int sum,
sum, count,
count, n1,
n1, n2;
n2;
int
void print_totals(
print_totals( int
int amt);
amt);
void
void main
main (( ))
void
{{
.. .. ..

Restof
offile
file
Rest

Name 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
void print_sum (int n1, int n2)
with same name { int sum;
sum = n1 + n2;
cout << sum; }
void main( )
{
float sum, x, y;
. . .
print_sum (x, 34);
. . .

30

Scope 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

31

Non-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
declared
int x, y, z;
void do_it (float x)
{ char y; . . .
z }
void main ( )
{ float y, z;
. . . x }

32

Scope 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

33

Side 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 globals in functions

34

Globals in Functions
Assign value to globals
Call function
Use globals
in function
Note -- according
to the instructor
this is generally
a bad practice!

35

36

Globals in Functions
This is a tempting way to go
especially when you dont 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

Global 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 ( )
{ . . .

37

Lifetime of a Variable

38

Defn => Period of time during program


execution when an identifier actually has
memory allocated to it
Variables local to
void print_sum (int n1, int n2)
a function not
{ int sum;
allocated space
sum = n1 + n2;
De-allocated
De-allocated
until the program
cout << sum; }
whenfunction
function
when
enters the
finishes
void main( )
finishes
function
{
float sum, x, y;
. . .
print_sum (24, 34);

Lifetime of a Variable
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;
}

Memory
Locals

Globals

x: 5
y : 17
.exe code
O.S.

39

Lifetime of a Variable
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;
}

a allocated

Memory
a: 0
Locals

Globals

x: 5
y : 17
.exe code
O.S.

40

Lifetime of a Variable
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;
}

a de-allocated

Memory
Locals

Globals

x: 5
y : 17
.exe code
O.S.

41

Lifetime of a Variable
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;
}

b allocated

Memory
b:2
Locals

Globals

x: 5
y : 17
.exe code
O.S.

42

Lifetime of a Variable
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;
}

b de-allocated

Locals

Globals

x: 5
y : 17
.exe code
O.S.

43

Lifetime 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

44

45

Automatic 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

46

Static Variables
By default, local variables are automatic.
To obtain a static local variable, you
must use the reserved work static in
its declaration.

47

Static and Automatic


Local Variables
int
int popularSquare(
popularSquare( int
int n)
n)
{{
static
static int
int timesCalled
timesCalled == 00 ;; //
// initialized
initialized
//
// only
only once
once
int
result
int
result == nn ** nn ;;
//
// initialized
initialized each
each time
time
timesCalled
timesCalled == timesCalled
timesCalled ++ 11 ;;
cout
cout <<
<< Call
Call ## <<
<< timesCalled
timesCalled <<
<< endl
endl ;;
return
return result
result ;;
}}

Static & Automatic Variables

Whatgets
getsprinted?
printed?
What

48

Function Overloading

49

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.

Function Overloading

50

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);

Functions 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()

51

Functions 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

52

Potrebbero piacerti anche