• No results found

Lec6 - Functions (II).pdf

N/A
N/A
Protected

Academic year: 2020

Share "Lec6 - Functions (II).pdf"

Copied!
25
0
0

Loading.... (view fulltext now)

Full text

(1)

Quiz!!

Write a function to compute the following series:

Write a test program that displays the following table:

i m(i)

1 0.5 2 1.1667 ...

19 16.4023 20 17.3546

1

...

3

2

2

1

)

(

i

i

i

m

Structured Programming

Using C++

(2)

Lecture Contents:

4-3

Scope Rules.

Parameters

Call-by-value

Call-by-reference

Mixed parameter-lists

Overloading and Default Arguments

Examples, Rules

Testing and Debugging Functions <optional>

assert Macro

Stubs, Drivers

Dr. Amal Khalifa, 2012

Scope rules

(3)

Functions & Memory Usage

Dr. Amal Khalifa, 2012 5

What really happens when you call a function?

Heap:

 “free store”, a large pool of memory used for dynamic allocation

Stack

 data structure that stores information about the active functions  supports the function call/return mechanism

 supports the creation, maintenance and destruction of each called

function's automatic variables.

 LIFO behavior

Function call stack

LIFO behavior:

• the caller pushes the

return address onto the stack,

• when it finishes, the

called function pops

the return address off the call stack

• Control is transfers to

that address.

• memory is finite -->

(4)

Dr. Amal Khalifa, 2012 7

Scope Rules…

Global

:

Declared "outside" function body
(5)

Global Variables

Dr. Amal Khalifa, 2012 9

Global declarations typical for constants:

 Declare globally so all functions have scope

 const double TAXRATE = 0.05;

 const double PI = 3.14159;

Global variables?

 Possible, but SELDOM-USED  Dangerous: no control over usage!

Local Variables

Local variables

 Declared inside body of given function or block of code  Available only within that function

 Can we have variables with same names declared in different

functions??

Local variables preferred

 Maintain individual control over data  Need to know basis

(6)

Blocks

11

Declare data inside compound statement

 Called a "block"  Has "block-scope"

Note: all function definitions are blocks!

 This provides local "function-scope" 

Loop blocks:

for (int ctr=0;ctr<10;ctr++)

{

sum+=ctr;

}

 Variable ctr has scope in loop body block only

Dr. Amal Khalifa, 2012

Nested Scope

Same name variables declared in multiple blocks

Very legal; scope is "block-scope"

No ambiguity

(7)

Procedural Abstraction

13

Need to know "what" function does, not "how" it

does it!

Think "black box"

Device you know how to use, but not it’s

method of operation

Implement functions like black box

User of function only needs: declaration

Does NOT need function definition

 Called Information Hiding

 Hide details of "how" function does it’s job

Dr. Amal Khalifa, 2012

Parameters

(8)

Parameters and Arguments

4-15

Confusing terms, often used interchangeably

True meanings:

Formal parameters

 In function declaration and function definition

Arguments

 Used to "fill-in" a formal parameter  In function call (argument list)

Dr. Amal Khalifa, 2012

Choosing Formal Parameter Names

Same rule as naming any identifier:

Meaningful names!

Functions as "self-contained modules"

Designed separately from rest of program

Assigned to teams of programmers

All must "understand" proper function use

OK if formal parameter names are same

as argument names

(9)

Parameters

4-17

Two methods of passing arguments as parameters

Call-by-value

reference

Call-by-Dr. Amal Khalifa, 2012

Call-by-Value Parameters

Copy of actual argument passed

Considered "local variable" inside function

If modified, only "local copy" changes

Function has no access to "actual argument” from caller

This is the default method

(10)

Example:

Dr. Amal Khalifa, 2012 4-19

Write function that computes the bill for a law

office. Each consultation hour costs $150.

(11)

Example:

Dr. Amal Khalifa, 2012 4-21

Call-by-Value Pitfall

Common Mistake:

Declaring parameter "again" inside function:

double

fee

(int hoursWorked, int

minutesWorked)

{

int quarterHours;

// local variable

int minutesWorked

// NO!

}

Value arguments ARE like "local variables"

(12)

Call-By-Reference Parameters

4-23

Specified by ampersand, &, after type in formal parameter list

What’s really passed in?

A "reference" back to caller’s actual argument!

Refers to memory location "address", of actual argument

Used to provide access to caller’s actual argument

Caller’s data can be modified by called function!

Typically used for input function

To retrieve data for caller

Data is then "given" to caller

Dr. Amal Khalifa, 2012

(13)

Example:

4-25 Dr. Amal Khalifa, 2012

Mixed Parameter Lists

Can combine passing mechanisms

void

mixedCall

(int & par1, int par2,

double & par3);

 arg1 must be integer type, is passed by reference  arg2 must be integer type, is passed by value  arg3 must be double type, is passed by reference

Order of arguments in list is critical

(14)

Example

Dr. Amal Khalifa, 2012 27

Write a function

isMultiple ,

for a pair of integers ,

that determines whether the second integer is a multiple of

the first. The function should also return the remainder of

division in case not .

Constant Reference Parameters

Reference arguments inherently "dangerous"

Caller’s data can be changed

Often this is desired, sometimes not

To "protect" data, & still pass by reference:

Use const keyword

 void sendConstRef(const int &par1, const int &par2);

(15)

Overloading

Same name, multiple actions!!

Dr. Amal Khalifa, 2012 29

Overloading

Same function name

Different parameter lists

Two separate function definitions

Function "signature"

Function name & parameter list

Must be "unique" for each function definition

(16)

Example: Average

• Which function gets

called?

• signature of function

• "Matches" call with

appropriate function

• Each considered

separate function

Dr. Amal Khalifa, 2012 4-31

double average(double n1,

double n2)

{

return ((n1 + n2) / 2.0); }

double average(double n1,

double n2, double n3)

{

return ((n1 + n2 + n3) / 3.0);

}

Overloading Pitfall

Only overload "same-task" functions

A mpg() function should always perform same task, in all

overloads

Otherwise, unpredictable results

C++ function call resolution:

1

st

: looks for exact signature:

 Where no argument conversion required

2

nd

: looks for "compatible" signature (

automatic type conversion)

 1st with promotion (e.g., intdouble)

(17)

Overloading Resolution Example

4-33

Given following functions:

1. void f(int n, double m);

2. void f(double n, int m);

3. void f(int n, int m);

These calls:

f(98, 99);

Calls #3

f(5.3, 4);

Calls #2

f(4.3, 5.2);

Calls ???

Avoid such confusing overloading

Dr. Amal Khalifa, 2012

Automatic Type Conversion

and Overloading

Numeric formal parameters typically

made "double" type

Allows for "any" numeric type

Any "subordinate" data automatically promoted

 int  double  float  double

 char  double *More on this later!

(18)

Automatic Type Conversion

and Overloading Example

4-35

double

mpg

(double miles, double

gallons)

{

return (miles/gallons);

}

Example function calls:

mpgComputed = mpg(5, 20);

mpgComputed = mpg(5.8, 20.2);

mpgComputed = mpg(5, 2.4);

Dr. Amal Khalifa, 2012

Default Arguments

Allows omitting some arguments

Specified in function declaration/prototype

void showVolume( int length,

int width = 1,

int height = 1);

Possible calls:

(19)

Example:

4-37 Dr. Amal Khalifa, 2012

(20)

Testing and debugging

Optional!!

Dr. Amal Khalifa, 2012 39

Testing and Debugging Functions

Many methods:

Lots of cout statements

 In calls and definitions  Used to "trace" execution

Compiler Debugger

 Environment-dependent

assert Macro

 Early termination as needed

Stubs and drivers

(21)

The assert Macro

4-41

Assertion: a true or false statement

Used to document and check correctness

Preconditions & Postconditions

 Typical assert use: confirm their validity

Syntax:

assert(<assert_condition>);

 No return value

 Evaluates assert_condition

 Terminates if false, continues if true

Predefined in library <cassert>

Macros used similarly as functions

Dr. Amal Khalifa, 2012

An assert Macro Example

void computeCoin(

int coinValue,

int& number,

int& amountLeft);

//Precondition: 0 < coinValue < 100

0 <= amountLeft <100

//Postcondition: number set to max. number

of coins

Check precondition:

assert ((0 < currentCoin) && (currentCoin < 100) && (0 <= currentAmountLeft) &&

(currentAmountLeft < 100));

 If precondition not satisfied  condition is false  program execution

(22)

assert On/Off

4-43

Preprocessor provides means

#define NDEBUG

#include <cassert>

Add "#define" line before #include line

Turns OFF all assertions throughout

program

Remove "#define" line (or comment out)

Turns assertions back on

Dr. Amal Khalifa, 2012

Stubs and Drivers

Separate compilation units

Each function designed, coded, tested separately

Ensures validity of each unit

Divide & Conquer

 Transforms one big task  smaller, manageable tasks

But how to test independently?

(23)

Example:

4-45 Dr. Amal Khalifa, 2012

(24)

Example:

Dr. Amal Khalifa, 2012 4-47

Stubs

Develop incrementally

Write "big-picture" functions first

Low-level functions last

"Stub-out" functions until implementation

Example:

double unitPrice(int diameter, double

price)

{

return (9.99);

// not valid, but

noticeably

// a "temporary" value

(25)

Fundamental Testing Rule

4-49

To write "correct" programs

Minimize errors, "bugs"

Ensure validity of data

Test every function in a program where every other function

has already been fully tested and debugged

Avoids "error-cascading" & conflicting results

Dr. Amal Khalifa, 2012

That’s all for today !!

References

Related documents