1 Chapter 9 Scope, Lifetime, and More on 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.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
1 Lecture 10 Chapter 7 Functions Dale/Weems/Headington.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 6 Functions.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
Overview creating your own functions calling your own functions.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Functions l Control structures l every C++ program must have a function called main l program execution.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 6: Functions by.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 7 Functions.
1 Chapter 7 Functions. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 Scope, Lifetime, and More on Functions. 2 Chapter 8 Topics  Local Scope vs. Global Scope of an Identifier  Detailed Scope Rules to Determine which.
1 Programming in C++ Dale/Weems/Headington Chapter 7 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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 6 Functions.
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.
Functions Why we use functions C library functions Creating our own functions.
18. DECLARATIONS.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 Functions every C++ program must have a function called main program execution always begins with function main any other functions are subprograms and.
Chapter 8 Functions. Chapter 8 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task l Using Function Arguments.
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.
1 Functions. 2 Chapter 7 Topics  Writing a Program Using Functional Decomposition  Writing a Void Function for a Task  Using Function Arguments and.
1 Chapter 9 Additional Control Structures Dale/Weems.
CS Midterm Study Guide Fall General topics Definitions and rules Technical names of things Syntax of C++ constructs Meaning of C++ constructs.
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.
Chapter 7 Functions CS185/09 - Introduction to Programming Caldwell College.
1 Chapter 7 Functions Dale/Weems/Headington. 2 Chapter 7 Topics l Writing a Program Using Functional Decomposition l Writing a Void Function for a Task.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
1 Brief Version of Starting Out with C++, 4th Brief Edition Chapter 6 Functions.
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.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
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.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Chapter 6 Functions. 6-2 Topics 6.1 Modular Programming 6.2 Defining and Calling Functions 6.3 Function Prototypes 6.4 Sending Data into a Function 6.5.
CHAPTER 8 Scope, Lifetime, and More on Functions.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
Chapter 8 Functions.
Modular Programming with Functions
chapter 8 Scope,Lifetime,and More on Functions
Chapter 7: User-Defined Functions II
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
6 Chapter Functions.
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.
Presentation transcript:

1 Chapter 9 Scope, Lifetime, and More on Functions

2 Chapter 8 Topics l Local Scope vs. Global Scope of an Identifier l Detailed Scope Rules to Determine which Variables are Accessible in a Block l Determining the Lifetime of a Variable l Writing a Value-Returning Function for a Task Some Value-Returning Functions with Prototypes in Header Files cctype and cmath l Creating and Using a Module Structure Chart l Stub Testing a Program

3 Scope of Identifier The scope of an identifier (or named constant) is the region of program code in which it is legal to use that identifier for any purpose

4 Local Scope vs. Global Scope l The scope of an identifier that is declared inside a block (this includes function parameters) extends from the point of declaration to the end of the block l The scope of an identifier that is declared outside of all namespaces, functions, and classes extends from point of declaration to the end of the entire file containing the program code

5 const float TAX_RATE = 0.05; // Global constant float tipRate; // Global variable void handle (int, float); // Function prototype using namespace std; int main () { int age; // age and bill local to this block float bill;. // a, b, and tax cannot be used here. // TAX_RATE and tipRate can be used handle (age, bill); return 0; } void handle (int a, float b) { float tax; // a, b, and tax local to this block. // age and bill cannot be used here. // TAX_RATE and tipRate can be used } 5

6 Detailed Scope Rules 1Function names have global scope 2A function parameter’s scope is identical to the scope of a local variable declared in the outermost block of the function body 3A global variable’s (or constant’s) scope extends from its declaration to the end of the file, except as noted in rule 5 4A local variable’s (or constant’s) scope extends from its declaration to the end of the block in which it is declared, including any nested blocks, except as noted in rule 5 5An identifier’s scope does not include any nested block that contains a locally declared identifier with the same name (local identifiers have name precedence)

7 Name Precedence Implemented by Compiler Determines Scope l When an expression refers to an identifier, n The compiler first checks the local declarations n If the identifier isn’t local, the compiler works outward through each level of nesting until it finds an identifier with same name where it stops l Any identifier with the same name declared at a level further out is never reached l If compiler reaches global declarations and still can’t find the identifier, an error message results

8 Namespace Scope l The scope of an identifier declared in a namespace definition extends from the point of declaration to the end of the namespace body, and its scope includes the scope of a using directive specifying that namespace

9 n Use a qualified name consisting of the namespace, the scope resolution operator :: and the desired the identifier alpha = std::abs(beta); n Write a using declaration using std::abs; alpha = abs(beta); n Write a using directive locally or globally using namespace std; alpha = abs(beta); 3 Ways to Use Namespace Identifiers

10 Name Precedence (or Name Hiding) l When a function declares a local identifier with the same name as a global identifier, the local identifier takes precedence within that function

11 Memory Allocation int someInt; // For the global variable int Square (int n) // For instructions in body { int result; // For the local variable result = n * n; return result; }

12 No Memory Allocation int Square (int n); // Function prototype extern int someInt; // someInt is defined in another file // and is thus global to everything in // this file

13 Lifetime of a Variable l The lifetime of a variable is the time during program execution in which an identifier actually has memory allocated to it

14 Lifetime of Local Automatic Variables l Their storage is created (allocated) when control enters the function l Local variables are “alive” while function is executing l Their storage is destroyed (deallocated) when function exits

15 Lifetime of Global Variables l Their lifetime is the lifetime of the entire program l Their memory is allocated when program begins execution l Their memory is deallocated when the entire program terminates

16 Automatic vs. Static Variable l Storage for automatic variable is allocated at block entry and deallocated at block exit l Storage for static variable remains allocated throughout execution of the entire program

17 Default Allocation l Local variables are automatic To obtain a static local variable, you must use the reserved word static in its declaration

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

Data Flow Determines Passing-Mechanism Incoming /* in */ Pass-by-value Outgoing /* out */ Pass-by-reference Incoming/outgoing Pass-by-reference /* inout */ Parameter Data Flow Passing-Mechanism 19

20 Prototype for float Function AmountDue() is a function with 2 parameters The first is type char, the other is type int float AmountDue (char, int); This function calculates and returns the amount due for local phone calls The char parameter contains either a ‘U’ or an ‘L’ indicating Unlimited or Limited service; the int variable contains the number of calls made Assume Unlimited service is $40.50 per month and limited service is $19.38 for up to 30 calls, and $.09 per additional call

21 float AmountDue (char kind, int calls) // Two parameters { float result; // One local variable const float UNLIM_RATE = 40.50, LIM_RATE = 19.38, EXTRA =.09; if (kind ==‘U’) result = UNLIM_RATE; else if ((kind == ‘L’) && (calls <= 30)) result = LIM_RATE; else result = LIM_RATE + (calls - 30) * EXTRA; return result; } 21

22 #include float AmountDue (char, int); // Prototype using namespace std; void main () { ifstream myInfile; ofstream myOutfile; int areaCode, phoneNumber, calls; int count = 0; float bill; char service;......// Open files while (count < 100) { myInfile >> service >> phoneNumber >> calls; bill = AmountDue (service, calls); // Function call myOutfile << phoneNumber << bill << endl; count++; } // Close files } 22

23 To handle the call AmountDue(service, calls) MAIN PROGRAM MEMORY TEMPORARY MEMORY for function to use Locations: calls bill service calls result kind ?‘U’ 23

24 Handling Function Call bill = AmountDue(service, calls); l Begins by evaluating each argument l A copy of the value of each is sent to temporary memory which is created and waiting for it l The function body determines result l Result is returned and assigned to bill

25 int Power (/* in */ int x, // Base number /* in */ int n) // Power // This function computes x to the n power // Precondition: // x is assigned && n >= 0 && (x to the n) <= INT_MAX // Postcondition: // Return value == x to the n power { int result; // Holds intermediate powers of x result = 1; while (n > 0) { result = result * x; n--; } return result; }

26 Syntax Template for Function Definition DataType FunctionName ( Parameter List ) { Statement. }

27 Using bool Type with a Loop... bool dataOK; // Declare Boolean variable float temperature;... dataOK = true; // Initialize the Boolean variable while (dataOK) {... if (temperature > 5000) dataOK = false; }

28 A Boolean Function bool IsTriangle ( /* in */ float angle1, /* in */ float angle2, /* in */ float angle3) // Function checks if 3 incoming values add up to // 180 degrees, forming a valid triangle // Precondition: // angle1, angle2, angle3 are assigned // Postcondition: // Return == true, f sum is within of // degrees // == false, otherwise { return (fabs(angle1 + angle2 + angle ) < ); }

29 Some Prototypes in Header File int isalpha (char ch); // If ch is an alphabet character, // Return value == nonzero // == zero, otherwise int isdigit (char ch); // If ch is a digit (‘0’ - ‘9’), // Return value == nonzero // == zero, otherwise int islower (char ch); // If ch is a lowercase letter (‘a’ - ‘z’), // Return value == nonzero // == zero, otherwise int isupper (char ch); // If ch is an uppercase letter (‘A’ - ‘Z’), // Return value == nonzero // == zero, otherwise 29

30 Some Prototypes in Header File double cos (double x); // Return value == trigonometric cosine of angle x // in radians double exp (double x); // Return value == the value e ( ) raised to // the power x double log (double x); // Return value == natural (base e) logarithm of x double log10 (double x); // Return value == common (base 10) logarithm of x double pow (double x, double y); // Return value == x raised to the power y 30

31 What will the function do with your argument(s)? The answer to this question determines whether your function parameter should be value or reference as follows...

32 /* in */ value parameter /* out */ reference parameter using & /* inout */ reference parameter using & Value vs Reference only uses its value assigns it a value changes its value If the function-- Function parameter should be-- NOTE: I/O stream variables and arrays are exceptions

33 Use Void or Value-Returning Functions? 1If it must return more than one value or modify any of the caller’s arguments, do not use a value-returning function 2If it must perform I/O, do not use a value-returning function 3If there is only one value returned, and it is Boolean, a value-returning function is appropriate 4If there is only one value returned, and that value will be used immediately in an expression, a value-returning function is appropriate 5When in doubt, use a void function; you can recode any value-returning function as a void function by adding an extra outgoing parameter 6If both void and value-returning are acceptable, use the one you prefer

34 Use Stubs in Testing a Program A stub is a dummy function with a very simple body, often just an output statement that this function was reached, and a return value (if any is required) of the correct type Its name and parameter list is the same as the function that will actually be called by the program being tested