1 Scope Lifetime Functions (the Sequel) Chapter 8.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

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.
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.
An Introduction to Programming with C++ Fifth Edition
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.
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.
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.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
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 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.
Variable Scope Storage Class Recursion
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.
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.
1 Chapter 9 Additional Control Structures Dale/Weems.
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.
Cosc175/module.ppt1 Introduction to Modularity Function/procedures void/value-returning Arguments/parameters Formal arguments/actual arguments Pass by.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
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.
A FIRST BOOK OF C++ CHAPTER 6 MODULARITY USING 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 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 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.
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.
A First Book of ANSI C Fourth Edition
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
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
Control Structures - Repetition
Chapter 9 Scope, Lifetime, and More on Functions
User Defined Functions
6 Chapter Functions.
Chapter 7: User-Defined Functions II
Scope of Identifier The Scope of an identifier (or named constant) means the region of program where it is legal to use that.
FOR statement a compact notation for a WHILE e.g. sumgrades = 0;
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

1 Scope Lifetime Functions (the Sequel) Chapter 8

2 We're BACK! This time with... Local variables Global variables Static variables Automatic variables Avoid Side Affects

3 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

4 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

5 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);... void print_sum (int n1, int n2) { int sum; sum = n1 + n2; cout << sum; } void main( ) { float sum, x, y;... print_sum (x, 34);...

6 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

7 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

8 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 block Local identifiers with same name as non- local … local take precedence

9 Function Declarations and Definitions Recall … –declaration is the prototype –definition is the heading and source code Declaration only states a name (and interface) so compiler knows Declaration does not use any memory in the code file Definition uses memory for the instructions

10 Variable Declarations and Definitions So far we have seen only definitions of variables –memory does get used/allocated int x, y, z; void do_it (float x) { char y;... } void main ( ) { float y, z;... }

11 Variable Declarations and Definitions It is possible to declare a variable –name it only –memory set aside somewhere else (in another file module) –no memory storage required in this file module –use extern extern int x, y, z; void do_it (float x) { char y;... } void main ( ) { float y, z;...

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

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

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

15 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; } Lifetime of a Variable O.S..exe code x: 5 y : 17 Globals Locals Memory

16 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; } Lifetime of a Variable O.S..exe code x: 5 y : 17 Globals a: 0 Locals a allocated Memory

17 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; } Lifetime of a Variable O.S..exe code x: 5 y : 17 Globals Locals a de-allocated Memory

18 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; } Lifetime of a Variable O.S..exe code x: 5 y : 17 Globals Locals b : 2 b allocated Memory

19 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; } Lifetime of a Variable O.S..exe code x: 5 y : 17 Globals Locals b de-allocated

20 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

21 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

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

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

24 Static & Automatic Variables What gets printed?

25 Initializations in Definitions Variables often need initialization with some starting value –set a total to zero –set a counter to 1 or 0 In C++ this can be done when the variable is declared –Possible because memory is being allocated at this time int total_val = 0, count = 1;

26 Interface Design Recall three possible ways of data flow in function parameters /* in */ use pass by value /* out */ use pass by reference with & /* in-out */ use pass by reference with & Also possible to have global variables that functions reference

27 Globals in Functions Assign value to globals Call function Use globals in function Assign value to globals Call function Use globals in function Note -- according to the instructor this is generally a bad practice!

28 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

29 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 changes of the identifier const int lines_per_page = 66; void main ( ) {...

30 Boolean Functions Possible to make your own type Use that type to declare a function which will return that value typedef int Boolean; const Boolean TRUE = 1; const Boolean FALSE = 0 Boolean between (int a, int b, int c) { if (a < b && b < c) return TRUE; else return FALSE; }

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

32 A Boolean Function Boolean 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, angle 3 are assigned // POSTCONDITION: // FCTNVAL== true, if sum is within of // degrees //== false, otherwise { return ( fabs( angle1 + angle2 + angle ) < ) ; } Note : check for closeness not equality How does this return a Boolean value?

33 Naming Functions Non-value-returning functions –They perform a task –Use a verb Value-returning functions –they represent a value –use a noun or adjective This helps the program self document with well chosen identifier names

34 Naming Functions return a maximum value calculate & print paycheck compute area of hexagon return Boolean value whether or not incoming value is valid calculate & print roots of quadratic int max_value (int a, int b); void print_paycheck(); float hex_area (float side); Boolean valid_value (int value); void print_quad_roots (float a, float b, float c); Write prototypes for functions below

35 Interface Design and Side Effects Purpose of a value-returning function –to return a single value Thus, use /* out */ or /* in-out */ reference parameters is... –misleading –improper If a function must return multiple values –use a void function –use multiple reference parameters

36 Ignoring a Function Value Possible to call a value-returning function as if it is a statement But, what happens? The return value is discarded Nothing happens!

37 Ignoring a Function Value Occasionally this is acceptable, desirable Some functions return a result status –if you want the result, call the function as if is a value –if you do NOT want the result, call it as if it is a statement Boolean do_whatever (... ) { if ( … ) return FALSE; else { cout <<... ;... return TRUE; } }

38 Recommendations on Functions If multiple values must be returned –use reference parameters Do NOT use reference parameters in value returning functions Do NOT do I/O in value returning functions When in doubt, use a void function with reference parameter

39 Stubs and Drivers Stubs –“dummy” functions for testing –contain an output statement “you are here” type message Driver –simple main function used to call another function being tested –permits direct control of testing process

40 Testing and Debugging Hints Make sure variables used for actual parameters are declared Define and plan pre- & post-conditions, parameter lists to avoid side affects Generally, try to avoid use of global variables “Undeclared identifiers may be merely misspelled Do not use same identifier in parameter list and in local variable list of a function

41 Testing and Debugging Hints Make sure value-returning function is of correct type Make sure value-returning function has a return statement Call value-returning functions as if a value Call void functions as if a statement Avoid reference parameters in value-returning functions Use temporary output statements to display on screen where you are and what important values are