User Defined Functions

Slides:



Advertisements
Similar presentations
Chapter 8 Scope, Lifetime and More on Functions. Definitions Scope –The region of program code where it is legal to reference (use) an identifier Three.
Advertisements

C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
C++ for Engineers and Scientists Third Edition
1 Chapter 9 Scope, Lifetime, and More on Functions.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 6: Modularity Using Functions. In this chapter, you will learn about: – Function and parameter declarations – Returning a single value – Returning.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
CHAPTER 5 FUNCTIONS I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
1 Functions Chapter 7 2 Hope you can function! What is R2D2 doing here? What is his function? Who is Nibble? Can he function? IS he a function? Who is.
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPS120: Introduction to Computer Science Functions.
CPS120: Introduction to Computer Science Lecture 14 Functions.
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
Functions Chapter 6. Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules Function: a collection.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
CHAPTER 8 Scope, Lifetime, and More on Functions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Chapter 8 Functions.
User-Written Functions
Chapter 7: User-Defined Functions II
Chapter 4: Writing Classes
Programmazione I a.a. 2017/2018.
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
6 Chapter Functions.
Classes and Objects.
Chapter 7: User-Defined Functions II
Review for Final Exam.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Submitted By : Veenu Saini Lecturer (IT)
Chapter 8 Functions.
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
Standard Version of Starting Out with C++, 4th Edition
Corresponds with Chapter 5
Methods and Data Passing
Presentation transcript:

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 Side Effects of Global Variables Static and Automatic Variables Function Overloading Functions with Default Parameters

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

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

We need to communicate to the functions Improving Functions We need to communicate to the functions

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

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

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

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

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

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

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

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

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

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

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?

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

Reference Parameters provide that capability

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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!

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

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

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

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.

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

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

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

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

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

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

Static Variables By default, local variables are automatic. To obtain a static local variable, you must use the reserved work static in its declaration.

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

Static & Automatic Variables What gets printed?

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.

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

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

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