80
C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 ok: Walter Savitch, "Absolute C++," Addison Wesley, 2002

C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

Embed Size (px)

Citation preview

Page 1: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

C/C++ Basics (III)

Function, Parameters and Overloading

Berlin Chen 2003

Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002  

Page 2: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

2

1. Function ( 函數 )

Page 3: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

3

Learning Objectives

• Predefined Functions– Those that return a value and those that don’t

• Programmer-defined Functions– Defining, Declaring, Calling– Recursive Functions

• Scope ( 範疇 ) Rules– Local variables– Global constants and global variables– Blocks, nested scopes

Page 4: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

4

Introduction to Functions

• Building Blocks of Programs

• Terminology in Programming Languages:– Procedures, subprograms, methods– In C++: functions

• I-P-O– Input – Process – Output– Basic subparts to any program– Use functions for these ‘pieces’

Page 5: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

5

Predefined Functions

• Libraries full of functions for our use!

• Two types:– Those that return a value

– Those that do not return a value

• Must ‘#include’ appropriate library– e.g.:

• <cmath>, <cstdlib> (Original ‘C’ libraries)• <iostream> (for cout, cin)

Page 6: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

6

Using Predefined Functions

• Math functions very plentiful– Found in library <cmath>– Most return a value (the ‘answer’)

• Example: theRoot = sqrt(9.0);– Components:

sqrt : name of library functiontheRoot : variable used to assign ‘answer’ to9.0 : argument or ‘starting input’ for function

– In I-P-O:• I : 9.0• P: ‘compute the square root’• O: 3, which is returned & assigned to theRoot

Page 7: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

7

The Function Call

• Back to this assignment:

theRoot = sqrt(9.0);

– The expression ‘sqrt(9.0)’ is known as afunction call, or function invocation

– The argument in a function call (9.0) can be aliteral, a variable, or an expression

– The call itself can be part of an expression:• bonus = sqrt(sales)/10;• A function call is allowed wherever it’s legal to use

an expression of the function’s return type

Page 8: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

8

The Function Call

#include <iostream>#include <cmath>using namespace std;int main( ){ const double COST_PER_SQ_FT = 10.50; double budget, area, lengthSide;

cout << "Enter the amount budgeted for your dog house $"; cin >> budget; area = budget/COST_PER_SQ_FT;

lengthSide = sqrt(area); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << "For a price of $" << budget << endl << "I can build you a luxurious square dog house\n"<< "that is " << lengthSide << " feet on each side.\n"; return 0;}

//Computes the size of a dog house that can be purchased//given the user budget.

Page 9: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

9

More Predefined Functions

• #include <cmath>– fabs()// Returns absolute value of a float

• #include <cstdlib>– Library contains functions like:– abs() // Returns absolute value of an int– labs()// Returns absolute value of a long int– rand() // Returns a random number of an int– srand() // No input, set seed for rand()– exit() // End program

Page 10: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

10

More Math Functions

• pow(x, y)– Returns x to the power y (double result)

E.g. x = 3.0, y = 2.0; result = pow(x, y); cout << result;

Here 9.0 is displayed since 3.02.0 = 9.0

– Notice this function receives two arguments

• Generally speaking, a function can have any number of arguments, of varying data types

Page 11: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

11

Even More Math Functions

NAME DESCRIPTION TYPE OF ARGUMENT

TYPE OF VAULE RETURNED

EXAMPLE VALUE LIBRARYHEADER

sqrt Square root double double sqrt(4.0) 2.0 cmath

pow Powers double double power(2.0,3.0) 8.0 cmath

abs Absolute value for int int int abs(7)abs(-7)

77

cstdlib

labs Absolute value for long long long labs(-70000) 70000 cstdlib

fabs Absolute value for long double double fabs(-7.5) 7.5 cmath

ceil Ceiling (round up) double double ceil(3.2)ceil(3.9)

4.04.0

cmath

floor Floor (round down) double double float(3.2)float(3.9)

3.03.0

cmath

exit End program int void exit(1); None cstdlib

rand Random number None int rand() varies cstdlib

srand Set seed for rand unsigned int void srand(42) None cstdlib

Page 12: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

12

Predefined Void Functions

• No returned value

• Performs an action, but sends no ‘answer’

• When called, it’s a statement itself exit(1); // No return value, so not assigned

• This call terminates program

• void functions can still have arguments

• All aspects same as functions that ‘returna value’– They just don’t return a value!

Page 13: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

13

The exit Function

• exit(Integer_Value)– End the program immediately

– Any Integer_Value can be used, but by convention,

• 1 is used for a call to exit that is caused by error• 0 is used in other cases

– Using function exit() must contain the following to directives

#include <cstdlib>

using namespace std;

Page 14: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

14

Random Number Generator

• Return ‘randomly chosen’ number• Used for simulations, games

rand()– Takes no arguments– Returns value between 0 & RAND_MAX

• Scaling– Squeezes random number into smaller range

rand() % 6• Returns random value between 0 & 5

• Shifting rand() % 6 + 1

• Shifts range between 1 & 6 (e.g.: die roll)

Page 15: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

15

Random Number Seed

• Pseudorandom numbers– Calls to rand() produce given ‘sequence’

of random numbers

• Use ‘seed’ to alter sequence srand(seed_value);– void function– Receives one argument, the ‘seed’– Can use any seed value, including system time:

srand(time(0));– time() returns system time as numeric value– Library <time> contains time() functions

Page 16: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

16

Random Examples

• Random double between 0.0 & 1.0:(RAND_MAX-rand())/(double)(RAND_MAX)– Type cast used to force double-precision divisi

on

• Random int between 1 & 6:rand() % 6 + 1– ‘%’ is modulus operator (remainder)

• Random int between 10 & 20:rand() % 11 + 10

rand(),srand(), andRAND_MAX aredefined in the library cstdlib.

#include <cstdlib>

using namespace std;

Page 17: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

17

Programmer-Defined Functions

• Write your own functions!

• Building blocks of programs– Divide & Conquer– Readability– Re-use

• Your ‘definition’ can go in either:– Same file as main()– Separate file so others can use it, too

Page 18: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

18

Components of Function Use

• Function Declaration or Function Prototype ( 函數宣告 或 函數原型 )

– Information for compiler– To properly interpret calls

• Function Definition– Actual implementation/code for what function d

oes

• Function Call– Transfer control to function

對 compiler 描述函數介面,若函數有傳回值則告訴 compiler傳回值的型態,並且告訴compiler 函數引數 的個數和型態

描述函數函數本身實際上如何完成計算 / 執行,以及傳回值。包括 2 部分:1. function header2. function body

Page 19: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

19

Function Declaration

• Also called function prototype• An ‘informational’ declaration for compiler• Tells compiler how to interpret calls

– Syntax:<return_type> FnName(<formal-parameter-list>);

– Example:double totalCost(int numberParameter,

double priceParameter);

• Placed before any calls– In declaration space of main() or an other function – Or above main() in global space

只要是合法的識別字或變數

名稱即可

最好在 Global Space 宣告

Page 20: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

20

Function Definition

• Implementation of function• Just like implementing function main()

– Example:double totalCost(int numberParameter,

double priceParameter){

const double TAXRATE = 0.05; double subTotal;

subtotal = priceParameter * numberParameter; return (subtotal + subtotal * TAXRATE);

}

• Notice proper indenting當函數執行完畢傳回值事先置於一特殊位置,如暫存器或記憶體,然後呼叫的函數就會從這個位置取回值,所以函數必須先宣告, compile 才知道要讀取多少個位元組

function header ,與 function declaration相似,但後面沒有分號 ;

function body

Page 21: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

21

Function Definition Placement

• Placed after function main()– NOT ‘inside’ function main()!

• Functions are ‘equals’; no function is ever‘part’ of another

• Formal parameters ( 形式參數 ) in definition– ‘Placeholders’ for data sent in

• ‘Variable name’ used to refer to data in definition

• return statement– Sends data back to caller

只要是合法的識別字或變數名稱即可

Page 22: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

22

Function Call

• Just like calling predefined function

bill = totalCost(number, price);

– Recall: totalCost returns double value– Assigned to variable named ‘bill’– Arguments here: number, price– Recall arguments can be literals, variables,

expressions, or combination

• In function call, arguments often called ‘actual arguments’– Because they contain the ‘actual data’ being sent

Page 23: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

23

Function Example#include <iostream>using namespace std;double totalCost(int numberParameter, double priceParameter);int main( ){ double price, bill; int number; cout << "Enter the number of items purchased: "; cin >> number; cout << "Enter the price per item $"; cin >> price; bill = totalCost(number, price); cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); cout << number << " items at " << "$" << price << " each.\n" << "Final bill, including tax, is $" << bill << endl; return 0;}

//Computes the total cost, including 5% sales tax,//on numberPar items at a cost of pricePar each.

double totalCost(int numberParameter, double priceParameter){ const double TAXRATE = 0.05; //5% sales tax double subtotal;

subtotal = priceParameter * numberParameter; return (subtotal + subtotal*TAXRATE);}

Function declarationalso called the function prototype

Function call

Function head

Function body

Function definition

Page 24: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

24

在函數宣告時,不一定要提供傳遞之參數的變數名稱,只要參數型態。亦即參數清單的變數名稱可有可無,而且不一定要與函數定義時實際用的變數名稱一樣。

Alternative Function Declaration

• Recall: Function declaration is ‘information’ for compiler

• Compiler only needs to know:– Return type– Function name– Parameter list

• Formal parameter names not needed:

double totalCost(int numberParameter, double priceParameter);

double totalCost(int, double);

– Still ‘should’ put in formal parameter names• Improves readability

兩種用法都可以

Page 25: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

25

Parameter( 參數 ) vs. Argument ( 引數 )

• Terms often used interchangeably• Formal parameters/arguments ( 形式參數 / 引數 )

– In function declaration– In function definition’s header

• Actual parameters/arguments ( 實際參數 / 引數 )

– In function call

• Technically, parameter is ‘formal’ piecewhile argument is ‘actual’ piece

傳遞給函數的值稱為實際引數或參數

接收傳遞過來的值的變數

C++ 標準

Page 26: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

26

Functions Calling Functions

• We’re already doing this!– main() IS a function!

• Only requirement:

– Function’s declaration ( 函數宣告 ) must appear first

• Function’s definition typically elsewhere– After main()’s definition– Or in separate file

• Common for functions to call many other functions

• Function can even call itself: ‘Recursion’ ( 遞迴 )

你可以在任何函數定義 (function definition)裡呼叫其他的函數 (function call) ,但是你不可以在某函數定義裡再放入其他函數定義。

Page 27: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

27

Parameter( 參數 ) vs. Argument ( 引數 )

double cub(double x);int main(){ ... double side=5.0; double volumn=cube(side); … …}

double cube(double x){ return x*x*x; }

產生稱為 side的變數,並將他設為 5

5

side

原始值

傳遞值 5 至 cube 函數

產生稱為 x 的數,並將它設為傳入之值 5

5

x

複製的值

Page 28: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

28

Parameter( 參數 ) vs. Argument ( 引數 )

在函數內宣告的變數,包括參數都是區域變數 (local variables)當函數被呼叫時電腦就會配置這些變數所需的空間,當函數結束時就會釋放這些變數使用的記憶體空間

void cheers(int n);int main(){ int n=150; int i=1000; int y=20; ... cheers(y); … …}

void cheers(int n){ for(int i=0;i<n;i++) cout <<“cheers!”; cout <<“\n”;};

每個函數有它自己的變數及它自己的值150 1000 20 0 20

Page 29: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

29

Arguments in the Wrong Type/Order

• Arguments in the Wrong Type– If you use an argument of the wrong type,

then, in many cases, some automatic type conversion will be done by C++

• However, the results may not be what you intended

• Arguments in the Wrong Order– If you confuse the order of arguments, the

program will not do what you want it to do• If there is a type variation, you will get an error

message when compiling• If there is no type variation, the program will

probably run normally by produce an incorrect result

Page 30: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

30

Boolean Return-Type Functions

• Function return-type can be any valid type• Boolean return-type

– Function declaration/prototype:

bool appropriate(int rate);

– Function definition:

bool appropriate (int rate){

return (((rate>=10)&&(rate<20))||(rate==0);}

– Returns true or false– Function call, from some other function:

if (appropriate(entered_rate)) cout << “Rate is valid\n”;

Page 31: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

31

Declaring Void Functions

• Similar to functions returning a value

• Return type specified as ‘void’

• Example:– Function declaration/prototype:

void showResults(double fDegrees, double cDegrees);

• Return-type is ‘void’ • Nothing is returned

A void function also canhave any number of arguments

告訴 compiler此函數執行完後將不回傳值

Page 32: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

32

Declaring Void Functions

• Function definition:void showResults(double fDegrees,

double cDegrees){

cout.setf(ios::fixed);cout.setf(ios::showpoint);cout.precision(1);cout << fDegrees

<< “ degrees fahrenheit equals \n”<< cDegrees << “ degrees celsius.\n”;

}

• Notice: no return statement– Optional for void functions

Page 33: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

33

Calling Void Functions

• Same as calling predefined void functions• From some other function, like main():

showResults(degreesF, degreesC);showResults(32.5, 0.3);

• Notice no assignment, since no valuereturned

• Actual arguments (degreesF, degreesC)– Passed to function– Function is called to ‘do it’s job’ with the

data passed in

Page 34: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

34

More on Return Statements

• Transfers control back to ‘calling’ function– For return type other than void, MUST have ret

urn statement– Typically the LAST statement in function

definition

• return statement optional for void functions– Closing “}” would implicitly return control from

void function在 void function 函數定義裡也可以有 return 的敘述,只是 return 的後面不用再有任何的運算式或數值。 return 的作用只是要來結束函數呼叫而已。其實 return 可以被在放在函數定義裡的任何位置。

Page 35: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

35

Function with No Arguments

• It is legal, and sometimes useful, to have a function with no arguments

void initializeScreen();

void initializeScreen(){ cout << “\n”;}

可填入 void 或者什麼都沒有

Page 36: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

36

Preconditions and Postconditions

• Similar to ‘I-P-O’ discussion– Comment function declaration:

void showInterest(double balance, double rate);//Precondition: balance is a nonnegative account //rate is the interest rate expressed as a percentage//Postcondition: amount of interest on given balance,// at given rate …

• Often called Inputs & Outputs

函數使用之註解

State what is assumed to be true when the function is called

Describe the effect of the function call

Page 37: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

37

main(): ‘Special’

• Recall: main() IS a function

• ‘Special’ in that:– One and only one function called main()

will exist in a program

• Who calls main()?– Operating system– Tradition holds it should have return statement– Value returned to ‘caller’ Here: operating s

ystem– Should return ‘int’ or ‘void’

You should not include a call to

main in your code!

Page 38: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

38

Scope ( 範疇 )Rules

• Local variables– Declared inside body of given function– Available only within that function– Have “that” function as their scope

• Can have variables with same namesdeclared in different functions– Scope is local: ‘that function is it’s scope’

• Local variables preferred– Maintain individual control over data– Need to know basis– Functions should declare whatever local data

needed to ‘do their job’

In the function definition

Page 39: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

39

Scope Rules#include <iostream>using namespace std;

double estimateOfTotal(int minPeas, int maxPeas, int podCount);//Returns an estimate of the total number of peas harvested.//The formal parameter podCount is the number of pods.//The formal parameters minPeas and maxPeas are the minimum//and maximum number of peas in a pod.

int main( ){ int maxCount, minCount, podCount; double averagePea, yield;

cout << "Enter minimum and maximum number of peas in a pod: "; cin >> minCount >> maxCount; cout << "Enter the number of pods: "; cin >> podCount; cout << "Enter the weight of an average pea (in ounces): "; cin >> averagePea; yield = estimateOfTotal(minCount, maxCount, podCount) * averagePea; ……..}

double estimateOfTotal(int minPeas, int maxPeas, int podCount){ double averagePea;

averagePea = (maxPeas + minPeas)/2.0; return (podCount * averagePea);}代表 weight

代表數目

Page 40: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

40

Procedural/Functional Abstraction

• Write and use functions as if they were black boxes

• Users 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

A function is like a small program!

Page 41: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

41

Global Constants and Global Variables

• Declared ‘outside’ function body– Global to all functions in that file

• Declared ‘inside’ function body– Local to that function

• Global declarations typical for constants: const double TAXRATE = 0.05;– Declare globally so all functions have scope

• Global variables?– Possible, but SELDOM-USED– Dangerous: no control over usage!

A named constant is in fact nothing but a

variable that is initialized to a value

and that cannot have their value changed .

但是 scope 還是限制在同一程式裡

Page 42: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

42

Global Constants and Global Variables

• The compiler allows wide latitude in where you place the declarations for your global named constants

• To aid readability, you should place all include directives together, all global named constant variable declarations together in another group, and all function declarations (function prototypes) together

• Follow standard practice to put all global named constant variables after include and using directives and before function declarations

程式寫作注意事項

Page 43: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

43

Blocks

• A block in C++ code enclosed in braces “{” “}” • Declare data inside a 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

Page 44: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

44

Nested Scope

• Same name variables declared in multiple blocks

• Very legal; scope is ‘block-scope’– No ambiguity– Each name is distinct withi

n it’s scope

void main(){ int i,j; for (i=0;i<10;i++) { int varA; varA=i; cout << "varA in Loop1:"<<varA<<"\n"; for (j=0;j<i;j++) { int varA; varA=j; cout <<"varA in Loop2:"<<varA<<"\n"; } //for j }//for I}

Page 45: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

45

Recursive Functions ( 遞迴函數 )

• A function definition that includes a call to itself is said to be recursive

#include <iostream>using namespace std;void countDown(int n);

void main(){

countDown(4);}

void countDown(int n){ cout << "Count dowm at level [%d] ..."<<n<<"\n"; if(n>0) countDown(n-1); cout << "Return at level [%d] "<< n <<"\n";}

Page 46: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

46

Summary 1

• Two kinds of functions:– ‘Return-a-value’ and void functions

• Functions should be ‘black boxes’– Hide ‘how’ details– Declare own local data

• Function declarations should self-document– Provide pre- & post-conditions in comments– Provide all ‘caller’ needs for use

Page 47: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

47

Summary 2

• Local data– Declared in function definition

• Global data– Declared above function definitions– OK for constants, not for variables

• Parameters/Arguments– Formal: In function declaration and definition

• Placeholder for incoming data

– Actual: In function call• Actual data passed to function

儘量少用 global 變數

Page 48: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

48

2. Parameters and Overloading

Page 49: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

49

Learning Objectives

• Parameters– Call-by-value ( 以值呼叫函數 )

– Call-by-reference ( 以參考值呼叫函數 )

– Mixed parameter-lists

• Overloading ( 多載 ) and Default Arguments– Examples, Rules

• Testing and Debugging Functions– assert Macro– Stubs, Drivers

Page 50: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

50

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– Used in all examples thus far

Page 51: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

51

Call-by-Value Parameters

• Example

int myCalculation(int inA){ inA=inA*inA; return inA;}

int myCalculation(int inA);

void main(){ int varA=30,varB; varB=myCalculation(varA); cout<<varB; ……}

產生稱為 varA 的變數,並將其值設為 30 ,將其值傳給函數 myCalculation

另外產生稱為 intA 的變數,將它設為傳入值 30

30 → 900

30 varA

inA

Memory

兩個變數名稱指到不同記憶體位址

Page 52: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

52

Call-by-Value Pitfall

• Common Mistake:• Declaring parameter ‘again’ inside function:

double fee(int hoursWorked, int minutesWorked){

int quarterHours; // local variableint minutesWorked; // NO!

}

• Compiler error results– “Redefinition error…”

• Value arguments ARE like ‘local variables’– But function gets them ‘automatically’

Page 53: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

53

Call-by-Reference Parameters

• Used to provide access to caller’sactual argument

• Caller’s data can be modified by calledfunction!– Typically used for input function– To retrieve data for caller

• Data is then ‘given’ to caller

• Specified by ampersand, &, after typein formal parameter list

Page 54: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

54

Call-by-Reference Parameters

• Example

void myCalculation(int &inA){ inA=inA*inA;}

void myCalculation(int &inA);

void main(){ int varA=30; myCalculation(varA); cout<<varA; ……}

產生稱為 varA 的變數,並將其值設為 30 ,將其值傳給函數 myCalculation

產生稱為 inA 的變數,為 varA 的別名

30 → 900 varA inA

Memory

兩個變數名稱指到相同記憶體位址

address

Page 55: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

55

Call-By-Reference Details

• What’s really passed in?

• A ‘reference’ back to caller’s actual argument !– Refers to memory location of actual argument– Called ‘address’, which is a unique number

referring to distinct place in memory

Page 56: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

56

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

• Makes arguments ‘read-only’ by function• No changes allowed inside function body

Page 57: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

57

Mixed Parameter Lists

• Can combine passing mechanisms

• Parameter lists can include pass-by-valueand pass-by-reference parameters

• Order of arguments in list is critical: void mixedCall(int & par1, int par2, double & par3);

• Function call: mixedCall(arg1, arg2, arg3);

• 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

Function Declaration

Function Call

Page 58: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

58

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 (actual) argument names

• Choose function names with same rules

Page 59: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

59

Overloading ( 多載 )

• Same function name

• Different parameter lists

• Two separate function definitions

• Function ‘signature’– Function name and parameter list– Must be ‘unique’ for each function definition

• Allows same task performed on differentdata

1 2

Page 60: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

60

Overloading Example: Average

• Function computes average of 2 numbers: double average(double n1, double n2)

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

}

• Now compute average of 3 numbers:double average(double n1, double n2, double n3){

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

• Same name, two functions

Page 61: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

61

Overloading Example: Average

• Which function gets called?

• Depends on function call itself: avg = average(5.2, 6.7);

• Calls ‘two-parameter average()’

avg = average(6.5, 8.5, 4.2);• Calls ‘three-parameter average()’

• Compiler resolves invocation based onsignature of function call– ‘Matches’ call with appropriate function– Each considered separate function

Page 62: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

62

Overloading Pitfall• Only overload ‘same-task’ functions

• The function mpg() //mile per gallon – should always perform same task, in all overlo

ads– Otherwise, unpredictable results

• C++ function call resolution:– 1st: looks for exact signature– 2nd: looks for ‘compatible’ signature

int mpg(int mile, int gallons);

int mpg(double mile, double gallons);

mpg(45, 2);

Page 63: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

63

Overloading Pitfall

• Don’t use the same function name for two uncorrelated functions

double mpg(double miles, double gallons )//return Miles Per Gallon.{ return (miles/gallons); ……}

int mpg(int goals, int misses )//return the Measure of Prefect Goals//which is computed as (goals - misses){ return (goals - misses ); ……}

cout<<mpg(45.0, 2.0) << “mile per gallon”;

cout<<mpg(45, 2) << “mile per gallon”;

What are the results ?

double mpg(double miles, double gallons ); int mpg(int goals, int misses );

Function Declarations

Function Definition Function Definition

Page 64: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

64

Overloading Resolution

• Example– 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 #3f(5.3, 4); Calls #2f(4.3, 5.2); Calls ???

– Avoid such confusing overloading

The compiler does not know which of the two arguments to convert to a value of type int, and a error message is

generated

Page 65: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

65

Automatic Type Conversion and Overloading

• Numeric formal parameters typicallymade ‘double’ type

• Allows for ‘any’ numeric type– Any ‘subordinate’ data automatically

promotedint double

float double

• Avoids overloading for different numerictypes

Page 66: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

66

Automatic Type Conversion and Overloading Example

double mpg(double miles, double gallons){

return (miles/gallons);}

• Example function calls: mpgComputed = mpg(5, 20);

• Converts 5 & 20 to doubles, then passes

mpgComputed = mpg(5.8, 20.2);• No conversion necessary

mpgComputed = mpg(5, 2.4);• Converts 5 to 5.0, then passes values to function

Function Definition

Page 67: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

67

Default Arguments

• Allows omitting some arguments • Specified in function declaration/prototype

void showVolume(int length,int width = 1,int height = 1);

• Last 2 arguments are defaulted

• Possible calls:showVolume(2, 4, 6); //All arguments suppliedshowVolume(3, 5); //height defaulted to 1showVolume(7); //width & height defaulted to 1

Function Declaration

Cannot omit the second argument in an invocation without also omitting the third argument!

Page 68: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

68

Default Argumentsexample

#include <iostream>using namespace std;void showVolume(int length, int width = 1, int height = 1);//Returns the volume of a box. //If no height is given, the height is assumed to be 1.//If neither height nor width are given, both are assumed to be 1.

int main( ){ showVolume(4, 6, 2); showVolume(4, 6); showVolume(4); return 0;}

void showVolume(int length, int width, int height){ cout << "Volume of a box with \n" << "Length = " << length << ", Width = " << width << endl << "and Height = " << height << " is " << length*width*height << endl;}

default arguments

A default arguments should not be given a second time.

Page 69: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

69

Default Arguments

• Default arguments are of limited value

• Default arguments cane be used with called-by-value parameters

• Anything you can do with default arguments can be done using overloading– Although using overloading is more lengthy in

program codes

Page 70: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

70

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• Incremental development

Page 71: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

71

The assert Macro

• 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

Page 72: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

72

An assert Macro Example• Given Function Declaration:

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 programexecution terminates!

Page 73: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

73

An assert Macro Example

• Useful in debugging

• Stops execution so problem can beinvestigated

Page 74: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

74

assert On/Off

• Preprocessor provides means

#define NDEBUG#include <cassert>

• Add ‘#define’ line before #include line• Turns OFF all assertions throughout

program• Remove ‘#define’ line (or comment it out //)

– Turns assertions back on

• Note! Assert is not a cure-all

Page 75: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

75

Stubs and Drivers

• Separate compilation units– Each function designed, coded, tested

separately– Ensures validity of each unit– Divide & Conquer– Transforms one big task smaller, manageab

le tasks

• But how to test independently?– Driver programs

• A special program written to test the functions• Temporal tools, quite minimal, need not have fancy

input routines

Page 76: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

76

Driver Program Example//Driver program for the function unitPrice.#include <iostream>using namespace std;double unitPrice(int diameter, double price);//Returns the price per square inch of a pizza.//Precondition: The diameter parameter is the diameter of the pizza //in inches. The price parameter is the price of the pizza.int main( ){ double diameter, price; char ans; do { cout << "Enter diameter and price:\n"; cin >> diameter >> price; cout << "unit Price is $" << unitPrice(diameter, price) << endl; cout << "Test again? (y/n)"; cin >> ans; cout << endl; } while (ans == 'y' || ans == 'Y'); return 0;}

double unitPrice(int diameter, double price){ const double PI = 3.14159; double radius, area;

radius = diameter/ (double)2; area = PI * radius * radius; return (price/area);}

The Driver Program

The Function to be tested

Page 77: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

77

Stubs

• Develop incrementally• Write ‘big-picture’ functions first

– Low-level functions last– ‘Stub-out’ ( 掐滅 ?) functions until implementatio

n– Example:

double unitPrice(int diameter, double price){

return (9.99); // not valid, but noticeably // a ‘temporary’ value

}– Calls to function will still ‘work’

Using simplified versions of the missing and untested functions.The simplified functions

called stubs.

Page 78: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

78

Fundamental Testing Rule

• To write ‘correct’ programs

• Minimize errors, ‘bugs’

• Ensure validity of data– Test every function in a program where ever

y other function has already been fully tested and debugged

– Avoids ‘error-cascading’ & conflicting results

Page 79: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

79

Summary 1

• Formal parameter is placeholder, filledin with actual argument in function call

• Call-by-value parameters are ‘localcopies’ in receiving function body– Actual argument cannot be modified

• Call-by-reference passes memoryaddress of actual argument– Actual argument can be modified– Argument MUST be variable, not constant

Page 80: C/C++ Basics (III) Function, Parameters and Overloading Berlin Chen 2003 Textbook: Walter Savitch, "Absolute C++," Addison Wesley, 2002

80

Summary 2

• Multiple definitions of same function namepossible: called overloading

• Default arguments allow function call to‘omit’ some or all arguments in list– If not provided default values assigned

• assert macro initiates programtermination if assertions fail

• Functions should be tested independently– As separate compilation units, with drivers – Stubs for incremental program development