Download presentation
Presentation is loading. Please wait.
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
Syntax for the declaration: void functionName (void) { statements } Syntax for the call: functionName(); void in the parameter list is optional The parentheses in the call is required, even when there are no parameters
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
We need to communicate to the functions
Improving Functions We need to communicate to the functions
7
Sending values to the functions with value parameters.
Improving Functions Sending values to the functions with 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 Actual 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
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
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 * ; } This takes care of informing the compiler 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 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
17
What is different in this version of the function?
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?
18
Reference Parameters It would be helpful to be able to have the functions communicate back to the calling module.
19
Reference Parameters provide that 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
Contrast Value & Reference Parameters
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 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
22
Reference Parameters 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 5 5 10
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 parameter change 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
Once the flow of control is inside function funOne( ), this is the memory picture: Changes made to parameter b will affect num2 in main
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 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
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 ...
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
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 Caused by
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
Note -- according to the instructor this is generally a bad practice!
Globals in Functions Assign value to globals Call function Use globals in function Note -- according to the instructor this is generally a 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 Side Effects
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
De-allocated when function finishes
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-allocated when function finishes
39
Lifetime of a Variable Memory Locals x: 5 y : 17 Globals .exe code
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: 5 y : 17 Globals .exe code O.S.
40
Lifetime of a Variable Memory a: 0 Locals x: 5 y : 17 Globals
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: 5 y : 17 Globals .exe code O.S. a allocated
41
Lifetime of a Variable Memory Locals x: 5 y : 17 Globals .exe code
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: 5 y : 17 Globals .exe code O.S. a de-allocated
42
Lifetime of a Variable Memory b : 2 Locals x: 5 y : 17 Globals
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: 5 y : 17 Globals .exe code O.S. b allocated
43
Lifetime of a Variable Locals x: 5 y : 17 Globals .exe code O.S.
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: 5 y : 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
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
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 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 ; }
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);
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()
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.