Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Scope Lifetime Functions (the Sequel) Chapter 8.

Similar presentations


Presentation on theme: "1 Scope Lifetime Functions (the Sequel) Chapter 8."— Presentation transcript:

1

2 1 Scope Lifetime Functions (the Sequel) Chapter 8

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

4 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

5 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

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

7 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

8 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

9 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

10 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

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

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

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

14 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

15 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

16 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

17 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

18 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

19 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

20 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

21 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

22 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

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

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

25 24 Static & Automatic Variables What gets printed?

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

27 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

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

29 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

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

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

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

33 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 0.000001 of // 180.0 degrees //== false, otherwise { return ( fabs( angle1 + angle2 + angle3 - 180.0 ) < 0.000001 ) ; } Note : check for closeness not equality How does this return a Boolean value?

34 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

35 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

36 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

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

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

39 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

40 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

41 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

42 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


Download ppt "1 Scope Lifetime Functions (the Sequel) Chapter 8."

Similar presentations


Ads by Google