Presentation is loading. Please wait.

Presentation is loading. Please wait.

User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.

Similar presentations


Presentation on theme: "User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference."— Presentation transcript:

1

2 User Defined Functions Chapter 7

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

4 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 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

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

6 5 Void Functions Without Parameters Consider a program which will print the following pattern: program ************************************************************ ********* Go Team *********** ************************************************************ ********* BEAT ETBU ********** ************************************************************Note The prototype The syntax of the declaration, the definition The syntax of the call Consider a program which will print the following pattern: program ************************************************************ ********* Go Team *********** ************************************************************ ********* BEAT ETBU ********** ************************************************************Note The prototype The syntax of the declaration, the definition The syntax of the call

7 6 Improving Functions We need to communicate to the functions

8 7 Improving Functions Sending values to the functions with value parameters.

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

10 9 Function Parameters Formal parameter declared in the function heading Actual parameter variable or expression listed in a call (invocation) of the function 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 <<... }

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

12 11 Function Declarations Why the prototypes? All identifiers (including function names) must be declared before they are used Compiler must know about the function 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); Parameters Function name Function type

13 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 the compiler of what it needs and defining the source code also

14 13 Syntax of the Parameter List In parentheses For each parameter specify type then name separate type-name pairs with commas 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) {... }

15 14 Value Parameters Defn => a formal parameter that receives a copy of the contents of the corresponding actual parameter void main ( ) {... print_summary (rpt_total);... } void print_summary (int total) {... cout <<... } 17

16 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 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

17 16 Value Parameters Consider … When we change the contents of the value parameter in the function … What (if anything) happens to the actual parameter? 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

18 17 Reference Parameters What if we wanted the actual parameter to change? C++ allows us to do this with reference parameters. 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?

19 18 Reference Parameters It would be helpful to be able to have the functions communicate back to the calling module.

20 19 Reference Parameters Reference Parameters provide that capability

21 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 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

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

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

24 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.  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.

25 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 parameter change the value of the actual parameter.  Stream variables (for example, ifstream and ofstream ) should be passed by reference  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

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

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

28 27 Value and Reference Parameters and Memory Allocation Likewise, for function funTwo( ) funTwo( ) funTwo( ) Changes made to x and w will affect num2 and ch, respectively Likewise, for function funTwo( ) funTwo( ) 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

29 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 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 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

30 29 Scope of Identifiers Global (or file) scope declared outside a block from point of declaration on to end of entire file 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

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

32 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 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

33 32 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 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;... } z x

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

35 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 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

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

37 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 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 Side Effects

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

39 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 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); 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-allocated when function finishes

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

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

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

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

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

45 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 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

46 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

47 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. By default, local variables are automatic. To obtain a static local variable, you must use the reserved work static in its declaration.

48 47 Static and Automatic Local 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 ; } 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 ; }

49 48 Static & Automatic Variables What gets printed?

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

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

52 51 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() 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()

53 52 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 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


Download ppt "User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference."

Similar presentations


Ads by Google