Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.

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.
Functions CS 308 – Data Structures. Function Definition Define function header and function body Value-returning functions return-data-type function-name(parameter.
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.
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.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
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.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
Functions Why we use functions C library functions Creating our own functions.
18. DECLARATIONS.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
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 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.
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.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
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.
Unit 3 Lesson 11 Passing Data and Using Library Functions Textbook Authors: Knowlton, Barksdale, Turner, & Collings PowerPoint Lecture by Dave Clausen.
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.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
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.
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.
1 Programming in C++ Dale/Weems/Headington Chapter 11 One-Dimensional Arrays.
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
C++ Data Types Simple Structured Address Integral Floating
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
Pointers, Dynamic Data, and Reference Types
6 Chapter Functions.
Chapter 7: User-Defined Functions II
Chapter 8 Functions.
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

Programming in C++ Dale/Weems/Headington Chapter 8 Scope, Lifetime, and More on Functions

Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that identifier for any purpose.

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

const float TAX_RATE = 0.05 ; // global constant float tipRate ; // global variable void handle ( int, float ) ; // function prototype int main (void) { 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

Detailed Scope Rules Function name has global scope. Formal parameter scope is identical to scope of a local variable declared in the outermost block of the function body. Global variable (or constant) scope extends from declaration to the end of the file, except as noted in rule 5. Local variable (or constant) scope extends from declaration to the end of the block where declared. This scope includes any nested blocks, except as noted in rule 5. An identifier’s scope does not include any nested block that contains a locally declared identifier with the same name (local identifiers have name precedence).

Name Precedence Implemented by Compiler Determines Scope When a statement refers to an identifier, the compiler first checks the local declarations. 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. Any identifier with the same name declared at a level further out is never reached. If compiler reaches global declarations and still can’t find the identifier, an error message results.

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

These allocate memory 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 ; }

These do NOT allocate memory int Square (int n) ; // function prototype extern int someInt ; // someInt is global // variable defined in // another file

Lifetime of a Variable The lifetime of a variable is the time during program execution when an identifier actually has memory allocated to it.

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

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

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

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

Program with several functions function prototypes main( ) function definition Square( ) function definition Cube( ) function definition

Value-returning functions #include <iostream.h> int Square (int) ; // prototypes int Cube (int) ; int main (void) { 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 ;

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

float AmountDue (char Kind, int Calls) // 2 formal 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 ; }

#include <iostream.h> #include <fstream.h> float AmountDue ( char, int ) ; // prototype void main (void) { 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

To handle the call AmountDue (Service, Calls) MAIN PROGRAM MEMORY Locations: 4000 4002 4006 200 ? ‘U’ Calls Bill Service TEMPORARY MEMORY for function to use 7000 7002 7006 Locations: Calls Result Kind

Handling function call Bill = AmountDue (Service, Calls); begins by evaluating each actual parameter. A copy of the value of each is sent to temporary memory which is created and waiting for it. The function body determines Result. Result is returned and assigned to Bill.

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 ;

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

Typedef Statement SYNTAX typedef ExistingTypeName NewTypeName ; EXAMPLE typedef int Boolean ;

Using Boolean type with a loop typedef int Boolean ; const Boolean true = 1 ; // define 2 Boolean constants const Boolean false = 0 ; . . . Boolean dataOK ; // declare Boolean variable float temperature ; dataOK = true ; // initialize the Boolean variable while ( dataOK ) { . . . if ( temperature > 5000 ) dataOK = false ; }

A Boolean Function Boolean IsTriangle ( /* in */ float angle1, // Function checks if 3 incoming values add up to 180 degrees, // forming a valid triangle // PRECONDITION: angle1, angle2, angle 3 are assigned // POSTCONDITION: // FCTNVAL == true, if sum is within 0.000001 of // 180.0 degrees // == false, otherwise { return ( fabs( angle1 + angle2 + angle3 - 180.0 ) < 0.000001 ) ; }

Some prototypes in header file < ctype.h > int isalpha (char ch); // FCTNVAL == nonzero, if ch is an alphabet letter // == zero, otherwise int isdigit ( char ch); // FCTNVAL == nonzero, if ch is a digit ( ‘0’ - ‘9’) // == zero, otherwise int islower ( char ch ); // FCTNVAL == nonzero, if ch is a lowercase letter (‘a’ - ‘z’) int isupper ( char ch); // FCTNVAL == nonzero, if ch is an uppercase letter (‘A’ - ‘Z’)

Some prototypes in header file < math.h > double cos ( double x ); // FCTNVAL == trigonometric cosine of angle x radians double exp ( double x ); // FCTNVAL == the value e (2.718 . . .) raised to the power x double log ( double x ); // FCTNVAL == natural (base e) logarithm of x double log10 ( double x ); // FCTNVAL == common (base 10) logarithm of x double pow ( double x, double y ); // FCTNVAL == x raised to the power y

“What will the function do with your actual argument?” The answer determines whether your formal parameter should be value or reference as follows . . .

What will the function do with your actual argument? IF THE FUNCTION-- FORMAL PARAMETER IS-- will only use its value will give it a value will change its value /* in */ value parameter /* out */ reference parameter using & /* inout */ reference parameter NOTE: I/O stream variables and arrays are exceptions