Download presentation
Presentation is loading. Please wait.
Published byJohnathan Fitzgerald Modified over 9 years ago
1
Slide 1 Chapter 3 Function Basics Written by Walter Savitch, UCSD Modified by Tsung Lee, NSYSU EE
2
Slide 2 Outline Introduction Predefined Functions Those that return a value and those that don’t Programmer-defined Functions Defining, declaring, calling functions Scope Rules Local variables Global constants and global variables Blocks, nested scopes
3
可再使用 (reuse) 一個觀念 形成此可再使用 (reuse) 的觀念 將此觀念放到一個模組 (module) 裏 此模組稱之為副程式 (subprogram) 在 C 與 C++ 裏,稱其為函數 (function) 在需要使用此觀念的程式位置 給定其名稱,引用(呼叫 (call) ) 此形成單位的觀念 Slide 3 concept A type A( ) { } concept A … A( ); // 引用 function A …
4
Slide 4 Introduction to Functions Functions ( 函數 ) are building blocks of programs Extract meaningful subparts into functions : modular programming Can be invoked (called 呼叫 ) one to many times Also called procedures( 程序 ), subprograms( 副程式 ), methods( 方法 ) Typical subpart : Input – Process – Output (I-P-O) Use functions for these ‘pieces’ Can group other subparts into functions Start call B A Input Processing Output End C Start A Input Processing Output C Start(B) End(B) B function B Input Processing Output D call B End D B * Input from outside * Prepare data for use * Output to outside * Collect data for use Modular programming
5
C++ function (subprogram) Divide-and-conquer ( 分割征服策略) a program design Divide a problem into a number of subproblems Divide the solving of a problem into the solving of subprograms Program solutions of the subproblems into subprograms Integrate these subprograms into a program (that can invoke the subprograms) Slide 5 AB CD P Problem decomposition AB CD P Solving methods Caller (sub)program … A( ) … …B( ) … C( ) … … … D( ) … A B C D P Subprograms
6
C++ function (subprogram) C++ functions ( 函數 ) are subprograms ( 副程式 ) A C++ function has a function body of processing flow (its task) It can be called (invoked) by a caller program Call and pass parameters to the C++ function The C++ function executes its function body Then, return result(s) to the caller Slide 6 Caller (sub)program … A(a, b) … … int A(int x, int y) { … return z; } P Subprogram Acall A a, b are passed to x, y return from A z is passed back execution
7
Functions (subprograms) can be formed with divide-and-conquer ( 切割征服) Divide a problem into subproblems The program of a problem can be composed of functions (subprograms) of these subproblems Slide 7 #include using namespace std; int main( ) { int numberOfLanguages; cout << "Hello reader.\n" << “Welcome to C++.\n”; cout << "How many programming languages have you used? "; cin >> numberOfLanguages; if (numberOfLanguages < 1) cout << "Read the preface. You may prefer\n" << "a more elementary book by the same author.\n"; else cout << "Enjoy the book.\n"; return 0; } greeting get number of languages give advice
8
Divide-and-conquer and subprograms Simpler program Easy-to-design Easy-to-read Can be reused Can be prepared in prior Slide 8 #include using namespace std; int main( ) { int numberOfLanguages; greeting( ); numberOfLanguages = get_languages( ); give_advice(numberOfLanguages); return 0; } void greeting( ) { cout << "Hello reader.\n" << “Welcome to C++.\n”; } int get_languages( ) { int n; cout << "How many programming languages have you used? "; cin >> n; return n; } void give_advice(int n) { if (n < 1) cout << "Read the preface. You may prefer\n" << "a more elementary book by the same author.\n"; else cout << "Enjoy the book.\n"; } call
9
Slide 9 Predefined Functions Libraries ( 程式庫 ) : full of functions! Must ‘#include’ appropriate library e.g.:, (Original ‘C’ libraries), (cout, cin) Actually include header files ( 標頭檔 ) : cmath.h, cstdlib.h, iostream.h
10
Slide 10 Predefined Functions Functions of two types Those that return a value of some data type Performs a calculation, and sends an ‘answer’ Receive k arguments Those that do not void Performs an action, but sends no ‘answer’ Receive k arguments // This call terminates program // and returns error code 1
11
Slide 11 Using Predefined Functions Math functions very plentiful Found in library Most return a value (the ‘answer’) Example: theRoot = sqrt(9.0); sqrt : name of library function 9.0 : argument ( 參數 ) or ‘starting input’ for function theRoot : variable used to assign ‘answer’ to In I-P-O: I = 9.0 P = ‘compute the square root’ O = 3.0, which is the returned value ( 回覆值 ) & is assigned to theRoot Input Calculate sqrt Output Start(sqrt) End(sqrt) function sqrt
12
Slide 12 The Function Call Back to this assignment: theRoot = sqrt(9.0); The expression ‘sqrt(9.0)’ is known as a function call( 函數呼叫 ), or function invocation The argument in a function call (9.0) can be: A literal, 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
13
Copyright © 2002 Pearson Education, Inc. Slide 13 A Larger Example 2.38 1.54
14
Slide 14 More Predefined Functions #include Library contains functions like: abs()// Returns absolute value of an int labs()// Returns absolute value of a long int fabs()// Returns absolute value of a float fabs() is actually in library Remember: libraries were added after C++ was ‘born’, in incremental phases Refer to appendices/manuals for details
15
Slide 15 More Math Functions pow(x, y) Returns x to the power y : x y double result, x = 3.0, y = 2.0; result = pow(x, y); // 3.0 2.0 cout << result; Here 9.0 is displayed since 3.0 2.0 = 9.0 Notice this function receives two arguments A function can have any number of arguments, of varying data types
16
Slide 16 Random Number Generator Return ‘randomly chosen’ number Used for simulations and games Usage Predefined function rand() int rand() Takes no arguments Returns value between 0 & RAND_MAX Scaling rand() % 6 Squeezes random number into smaller range (between 0 & 5) Shifting rand() % 6 + 1 // Shifts range between 1 & 6 (e.g.: die roll) rand() % 10 + 10 // Random int between 10 & 20 Produce a random double between 0.0 & 1.0 rand() / static_cast (RAND_MAX) Type cast used to force double-precision division
17
Slide 17 Random Number Seed Pseudorandom numbers Calls to rand() produce given ‘sequence’ of random numbers Use ‘seed’ to alter sequence, or set up a pseudo random 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 Seconds since Jan. 1, 1970 Library contains time() functions Generates a sequence of 10 random numbers Generates the same random number sequence
18
Copyright © 2002 Pearson Education, Inc. Slide 18 Random Function Example
19
Slide 19 Sample Dialogue
20
Slide 20 Outline Introduction Predefined Functions Those that return a value and those that don’t Programmer-defined Functions Defining, declaring, calling functions Scope Rules Local variables Global constants and global variables Blocks, nested scopes
21
Slide 21 Programmer-Defined Functions Write your own functions! Build (extract) meaningful blocks into functions Divide & Conquer Readability Re-use Your function ‘definition’ can store in Same file as main() Separate file so others can use it, too
22
Slide 22 Function Use Need 3 Pieces to use functions Function declaration (function prototype) : declare it FnName( ); Information for compiler Placed before any calls (usually in the beginning) to properly interpret calls E.g.int max(int x, int y); Function definition : define it FnName( ) { function_body_statements } Actual implementation/code for what function does E.g. int max(int x, int y) { if (x > y) return x; else return y; } Function call : use it in program … FnName(argument-list) … Transfer control to function E.g. k = a + b * max(c, 20);
23
Slide 23 Example of Function Use Function declaration double totalCost(int numberParameter, double priceParameter); Function definition double totalCost(int numberParameter, double priceParameter) { const double TAXRATE = 0.05; double subTotal; subtotal = priceParameter * numberParameter; return (subtotal + subtotal * TAXRATE); } Function call bill = totalCost(number, price); call arguments – actual parameters replaced by the return value formal parameters( 參數 ) function body return result type of returned value
24
Slide 24 Function Declaration Compiler only needs to know: Return type Function name Parameter list Formal parameter names not needed: double totalCost(int, double); Still ‘should’ put in formal parameter names Improves readability
25
Slide 25 Function Definition Placed after function main() NOT ‘inside’ function main()! No function is ever ‘part’ of another Formal parameters in function definition Parameter variables are ‘Placeholders’ for data sent in i.e. Argument values are copied to parameter variables return statement Sends data back to caller
26
Slide 26 Function Example
27
Slide 27 Parameter vs. Argument Formal parameters or arguments In function declaration In function definition’s header Actual parameters or arguments In function call Technically Parameter is ‘formal’ piece Argument is ‘actual’ piece*
28
Slide 28 Boolean Return-Type Functions Return-type can be any valid type (here is bool) Function declaration/prototype: bool appropriate(int rate); Function’s 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”;
29
Slide 29 Void Functions Functions return no value Function declaration / prototype void showResults (double fDegrees, double cDegrees); Return type is void 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”; } No return statement Or with return statement with no return value return;
30
Slide 30 Void Functions Function call showResults(degreesF, degreesC); showResults(32.5, 0.3); Notice no assignment, since no value returned Actual arguments : (degreesF, degreesC) or (32.5, 0.3); Passed to function’s (fDegrees, cDegrees) Function is called to ‘do it’s job’ with the data passed in
31
Slide 31 More on Return Statements Transfers control back to ‘calling’ function For return type other than void MUST have return statement to return control with result For void functions return; statement return control with no result Or return statement is optional Closing } would implicitly return control from void function compiler insert return; statement there
32
Copyright © 2002 Pearson Education, Inc. Slide 32 Function Example
33
Slide 33 Functions Calling Functions We’re already doing this! main() IS a function! Common for functions to call many other functions Function can even call itself ‘Recursion’ Only requirement Function’s declaration must appear first
34
Slide 34 Preconditions and Postconditions Comment function declaration: Precondition : conditions of input parameters Postcondition : conditions of output (returned) results void showInterest(double balance, double rate); //Precondition: balance is nonnegative account balance //rate is interest rate as percentage //Postcondition: amount of interest on given balance, //at given rate … As function specification Good for software engineering Check for correctness Reused by self or other programmers
35
Slide 35 main( ) Function main() IS a function One and only one function called main() in a program Who calls main()? Operating system Should return ‘int’ or ‘void’ int returned value as program exit code Value returned to ‘caller’ Here: operating system
36
Slide 36 Outline Introduction Predefined Functions Those that return a value and those that don’t Programmer-defined Functions Defining, declaring, calling functions Scope Rules Local variables Global constants and global variables Blocks, nested scopes
37
Slide 37 Scope Rules Variable’s scope ( 範疇 ) : where it can be used Global scope ( 全域範疇 ) Function scope ( 函數範疇 ) Block scope ( 區塊範疇 ) Nested scope ( 巢狀範疇 )
38
Slide 38 Contour model of scopes Variable and parameter declarations are organized in nested contours Variable and parameter usages can refer from its containing contour outward The first contour contains the variable with the same name is used PI main( ) area( ) volume( ) cin, cout, … pow( ), … radius radiusOfBoth areaOfCircle volumeOfSphere Global scope main( ) scope area( ) scope volume( ) scope
39
Slide 39 Global Scope Declarations ‘outside’ any function body Global to all functions in that file Can be used by any statements globally 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!
40
Slide 40 Example of Global Scope declarations in scopes
41
Slide 41 Scope of example Global scope main( ) scope area( ) scope volume( ) scope PI main( ) area( ) volume( ) cin, cout, … pow( ), … radius radiusOfBoth areaOfCircle volumeOfSphere
42
Slide 42 Function Scope Local variables ( 區域變數 ) Declared inside body of given function Available only within that function Can have variables with same names declared in different functions Scope is local: ‘that function is it’s scope’ Local variables are preferred Maintain individual control over data Need-to-know basis Functions should declare whatever local data needed to ‘do their job’
43
Copyright © 2002 Pearson Education, Inc. Slide 43 Example of Function Scope declarations in scopes
44
Slide 44 Scope of example Global scope main( ) scope estimateOfTotal( ) scope main( ) estimatOfTotal( ) cin, cout, … minPeas, maxPeas, podCount averagePea minCount, maxCount, podCount averagePea, yield
45
Slide 45 Block Scope Declare data inside compound statement { … } Called a ‘block’ { … } The variables in has ‘block-scope’ Those variables can only be used inside the block 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
46
Slide 46 Nested Scope Variables defined in a block can be used in the inner nested blocks for (int i = 0; i < 100 ; i++) { for (int j = 0; j < 200 ; j++) { int k; k = i + j; cout << k << endl; } cout << i << endl; } the outer block’s i variable Outer block scope Inner block scope i jkjk
47
Slide 47 Scope of example Outer block scope Middle block scope Inner block scope x1 x3 x2
48
Slide 48 Nested Scope Same name variables declared in multiple nested blocks Very legal; scope is ‘block-scope’ No ambiguity Each name is distinct within it’s scope for (int i = 0; i < 100 ; i++) { for (int j = 0; j < 200 ; j++) { int i, k; cin >> i; k = i + j;// the inner i cout << k << endl; } cout << i << endl; // the outer i } Outer block scope Inner block scope i jikjik
49
Slide 49 Procedural Abstraction Need to know ‘what’ function does, not ‘how’ it does it! Think ‘black box’ Implement functions like black box (Information Hiding) Hide details of ‘how’ function does it’s job Not use global variables in functions Only use parameter variables and local variables Users to use the function Only needs: declaration – above box or function prototype type0 function_name(type1 par_var1, …); Does NOT need function definition Uses Implementers designs its details Users only need to know its interface Func_name Type1 par_var1 Type2 par_var2 Type0 result Typek par_vark
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.