1 / 52

User Defined Functions

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

salena
Télécharger la présentation

User Defined Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. User Defined Functions Chapter 7

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

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

  4. Void Functions Without Parameters voidin the parameter list is optional The parentheses in the call is required, even when there are no parameters • Syntax for the declaration: void functionName (void) { statements } • Syntax for the call:functionName();

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

  6. Improving Functions We need to communicate to the functions

  7. Improving Functions Sending values to the functionswith value parameters.

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

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

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

  11. Function Declarations Parameters Function type Function name • 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);

  12. Function 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; . . . } This takes care of informing thecompiler of what it needs and defining the source code also

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

  14. Value Parameters • 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 << . . . }

  15. Value 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

  16. Value Parameters No, nothing happens.The actual parameter remains unchanged • Consider … When we change the contents of the value parameter in the function … • What (if anything) happens to the actual parameter?

  17. Reference 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?

  18. Reference Parameters It would be helpful tobe able to have the functionscommunicate back to thecalling module.

  19. Reference Parameters Reference Parameters providethat capability

  20. Reference 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 View example program

  21. 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 Contrast Value & Reference Parameters Reference Value

  22. Reference Parameters 10 5 5 • Recall our previous model for a function with value parameters(values go in only) • Now consider a new version for reference parametersValues go bothin & out

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

  24. Value and Reference Parameters and Memory 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 parameterchange the value of the actual parameter. • Stream variables (for example, ifstream and ofstream) should be passed by reference

  25. Value and Reference Parameters and Memory Allocation • Note Example Program 7-6 • Before function is called, this is the memory picture

  26. Value and Reference Parameters and Memory Allocation Changes made to parameter b will affect num2 in main • Once the flow of control is inside function funOne( ),this is the memory picture:

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

  28. Scope of Identifiers • Scope <=> the region of program code where it is legal to reference (use) an identifier • Localscope <=> 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; . . . } Block

  29. Scope 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 ( ) { . . . Rest of file

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

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

  32. Non-Local Accessible When ... z x • 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; . . . }void main ( ) { float y, z; . . . }

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

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

  35. Globals in Functions • Assign value to globals • Call function • Useglobals in function Note -- accordingto the instructorthis is generallya bad practice!

  36. Globals 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 SideEffects

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

  38. Lifetime 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); De-allocatedwhen functionfinishes

  39. Lifetime of a Variable Memory 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;} Locals x: 5y : 17 Globals .exe code O.S.

  40. Lifetime of a Variable Memory 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: 0 Locals x: 5y : 17 Globals .exe code O.S. a allocated

  41. Lifetime of a Variable Memory 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;} Locals x: 5y : 17 Globals .exe code O.S. a de-allocated

  42. Lifetime of a Variable Memory 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 : 2 Locals x: 5y : 17 Globals .exe code O.S. b allocated

  43. 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;} Locals x: 5y : 17 Globals .exe code O.S. b de-allocated

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

  45. 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 Automatic vs. Static Variable

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

  48. Static & Automatic Variables What gets printed?

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

  50. Function 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);

More Related