1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.

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.
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.
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 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
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.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
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.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
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.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
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.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
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 Lecture 19 Structs HW 5 has been posted. 2 C++ structs l Syntax:Example: l Think of a struct as a way to combine heterogeneous data values together.
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.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING FUNCTIONS.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
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.
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
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.
Chapter 8 Functions.
Modular Programming with Functions
Test 2 Review Outline.
chapter 8 Scope,Lifetime,and More on Functions
Chapter 7: User-Defined Functions II
User-Defined Functions
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
Chapter 7: User-Defined Functions II
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 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington

2 Scope of Identifier l Where declared determines scope and lifetime n the scope of an identifier (or named constant) - the region of program code where it is legal to use that identifier for any purpose – compile-time issue n lifetime of an identifier - the period of time during program execution that memory is allocated – run-time issue l Local - declared inside block - cannot be accessed outside the block

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

4 l Function names - global l Scope of function parameter - local l Scope of global - from declaration to end of file l Scope of local - from declaration to end of block

5 Name Precedence Implemented by Compiler Determines Scope l When an expression refers to an identifier, the compiler first checks the local declarations. l If the identifier isn’t local, compiler works outward through each level of nesting until it finds an identifier with same name. There 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.

6 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

7 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

8 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 l Usually make constants global n Ease of change – in same place n Consistency – whole program uses same values

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

10 These allocate memory int iSomeInt ; // for the global variable int Square (int n) // for instructions in body { int result ; // for the local variable result = n * n ; return result ; }

11 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

12 By default l local variables are automatic to obtain a static local variable, you must use the reserved word static in its declaration. l Static local variable – lifetime of global but scope of local l Initializations in declarations l Global variables - program errors l Side effects

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

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

15 Program with Several Functions Square function Cube function function prototypes main function

Value-returning Functions #include int Square ( int ) ; // prototypes int Cube ( int ) ; using namespace std; int main ( ) { cout << “The square of 27 is “ << Square (27) << endl; // function call cout << “The cube of 27 is “ << Cube (27) << endl; // function call return 0; }

Rest of Program int Square ( int n ) // header and body { return n * n; } int Cube ( int n ) // header and body { return n * n * n; }

18 Prototype for float Function called AmountDue( ) with 2 parameters The first is type char, the other is type int. float AmountDue ( char, int ) ; This function will find and return the amount due for local phone calls. A char value ‘U’ or ‘L’ indicates Unlimited or Limited service, and the int holds the number of calls made. Assume Unlimited service is $40.50 per month. Limited service is $19.38 for up to 30 calls, and $.09 per additional call.

19 float AmountDue (char kind, int calls) // 2 parameters { float result ; // 1 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 ; }

20 #include float AmountDue ( char, int ) ; // prototype using namespace std ; void main ( ) { ifstream myInfile ; ofstream myOutfile ; int areaCode, Exchange, 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 }

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

22 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 – if not, answer is discarded

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

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

25 Built-in functions Function name – noun – returns a value Parameters – all value type – all incoming – only outgoing is result - return When to use value-returning functions

26 Use Stubs in Testing a Program Modular design – test program before all coded 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 a function that will actually be called by the program being tested.

27 Use Drivers in Testing a Program Modular design – test program before all coded A Driver is used to call the module itself Both are important in team programming

28 A Stub for Function GetYear void GetYear ( /* inout */ ifstream dataIn, /* out */ string& year ) // Stub to test GetYear function in ConvertDates program. // PRECONDITION: dataIn assigned // POSTCONDITION: year assigned { cout << “GetYear was called. Returning \”1948\”.” << endl ; year = “1948” ; }