Functions Scope local global Global Resolution Operator part II

Slides:



Advertisements
Similar presentations
1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
Advertisements

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.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Chapter 6: Functions.
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.
Functions g g Data Flow g Scope local global part 4 part 4.
Functions Structured Programming 256 Chapter 6 Functions g prototypes g arguments g overloading g return values part I.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
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)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
1 Value Returning Functions // Function prototype int Largest(int num1, int num2, int num3); Function Name Type Parameters Type of parameters Formal parameters.
CS102 Introduction to Computer Programming Chapter 6 Functions Continued.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
 2007 Pearson Education, Inc. All rights reserved Random Number Generation  rand function – Load – Returns "random" number between
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Cosc175/module.ppt1 Introduction to Modularity Function/procedures void/value-returning Arguments/parameters Formal arguments/actual arguments Pass by.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Functions g g Data Flow g Scope local global part II g Global Resolution Operator part II.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Week 11 Multi-file Programs and Scope of Variables.
#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 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.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
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.
CSC141- Introduction to Computer Programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 12.
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 CS1430: Programming in C++ Section 2 Instructor: Qi Yang 213 Ullrich
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
1 Scope Lifetime Functions (the Sequel) Chapter 8.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
User-Defined Functions (cont’d) - Reference Parameters.
CHAPTER 8 Scope, Lifetime, and More on Functions.
Functions Modules in C++ are called functions and classes. Main reason to use functions is : – get aid in conceptual organization.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Chapter 6 Modularity Using Functions
Functions Scope local global Global Resolution Operator part 5.
IS Program Design and Software Tools Introduction to C++ Programming
C Functions -Continue…-.
A Lecture for the c++ Course
CSC113: Computer Programming (Theory = 03, Lab = 01)
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Scope of Variables The region of code where it is legal to reference (use) an identifier. Local Scope Global Scope Class Scope.
Scope, Parameter Passing, Storage Specifiers
Chapter 9 Scope, Lifetime, and More on Functions
Scope Rules and Storage Types
Variables have attributes
Multiple Files Revisited
CS1201: Programming Language 2
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;
STORAGE CLASS.
Functions Chapter No. 5.
Presentation transcript:

Functions Scope local global Global Resolution Operator part II Data Flow Scope local global Global Resolution Operator part II

Data Flow Data flow is the direction of the information flow between the function and its caller. Adding data flow documentation to the function interface is helpful. The flow could be into a function, out of a function or both.

Parameter and Data Flow pass data into a function /* in */ pass data out of a function /* out */ pass data into and out of a function /* inout */

Parameter and Data Flow Examples void myFunction( /* in */ double nana, /* in */ int count) void yourFunction( /* out */ int& num1, /* out */ int& num2) void ourFunction( /* in */ int alpha, /* inout */ int& beta)

Parameter and Data Flow To be certain a function does what you want it to do, write value of variables as you enter and exit a function. Put the output statement into a function and call it whenever you need it. void ShowIt(void) { cout<< var1<< ‘\t’ <<var2<< ‘\t’ <<var3<< ‘\n’; } *

Parameter and Data Flow Flow In & out & int media( /* in */ int cow) { cout << “Ten * cow = “ << cow*10; return (2*cow +5); } int media( /* in */ int cow) { cow = 2 * cow; return (2*cow +5); } *

Parameter and Data Flow Flow Out void media( /* out */ float& delta, /* out */ float& epsilon ) { delta = 1.0; epsilon = 0.0002; } inout epsilon = epsilon - 0.0001; epsilon = epsilon - 0.0001; *

Parameter and Data Flow Flow In and Out void update( /* inout */ int& javel, /* inout */ int & grenelle ) { javel = 3 * javel; grenelle++; }

Data Flow - Example #include<iostream.h> void getTemp(double&); void activity(double); void convertCtoF(double&); void main(void) { double temperature; getTemp(temperature); activity(temperature); }

Data Flow - Example out inout * * void getTemp(/* */ double& temp) { cout<<"Enter the temperature in degrees C: "; cin>> temp; cout<<"The current temperature is " <<temp<<" degrees celsius."<<endl; convertCtoF(temp); } void convertCtoF( /* */ double& temp) temp=(1.8)*temp +32; cout<<"This equals "<<temp <<" degrees Fahrenheit."<<endl; inout * *

Data Flow - Example in * void activity(/* */ double temp) { cout<<"The recommended activity is "; if(temp>85) cout<<"swimming."<<endl; else if(temp>70) cout<<"tennis."<<endl; else if(temp>35) cout<<"golf."<<endl; else if(temp>10) cout<<"skiing."<<endl; else cout<<"dancing."<<endl; } in *

Data Flow data flow parameter-passing for a parameter mechanism incoming pass-by-value outgoing pass-by-reference incoming/outgoing pass-by-reference

I/O Example void main(void) { } 1 int red, blue; 2 void Mix( int&, int ); // prototype 3 int Blend( int, int ); // prototype 4 red = 5; 5 blue = Blend(3, red + 1); 6 Mix(red, blue); 7 cout << red << ' ' << blue << '\n'; 8 Mix(red, blue + red); 9 cout << red << ' ' << blue << '\n'; 10 Mix(red, Blend(blue, red)); 11 cout << red << ' ' << blue << '\n'; }

I/O Example { << yellow << ‘\n’; } M void Mix( int& green, int yellow) { M1 int purple; M2 cout << “enter Mix “ << green << ‘ ‘ << yellow << ‘\n’; M3 purple = green + yellow; M4 yellow = purple + yellow; M5 green = purple; M6 cout << “leav Mix “ << green << ‘ ‘ }

I/O Example { << green << ‘\n’; } B int Blend( int red, int green ) { B1 int yellow; B2 cout << “enter Blend “ << red <<‘ ‘ << green << ‘\n’; B3 yellow = red + green; B4 cout << “leave Blend “ << red <<‘ ‘ B5 return (yellow + 1); }

I/O Example inout void Mix( /* ______ */ int& green, /* ______ */ int yellow ) int Blend( /* ______ */ int red, /* ______ */ int green ) inout in in in * * * *

I/O Example The lines are executed in this order. 1 2 3 4 5 B B1 - B5 6 M M1 - M6 7 8 M M1 - M6 9 10 M B B1 - B5 M1 - M6 11 * * * *

I/O Example Mix memory Main green red blue yellow purple

Main Mix Blend * enter Blend 3 6 leave Blend 3 6 enter Mix 5 10 leave Mix 15 25 15 10 enter Mix 15 25 leave Mix 40 65 40 10 enter Blend 10 40 leave Blend 10 40 enter Mix 40 51 leave Mix 91 142 91 10 *

Scope A function is like a black box: You know what goes in and what comes out, but you do not know what happens inside the box.

Scope The section of the program where the variable is valid (known or visible). local = available to only one function global = available several functions

Scope Local: The scope of an identifier declared inside a block extends from the point of declaration to the end of that block. Global: The scope of an identifier declared outside all functions and classes extends from the point of declaration to the end of the source file. * *

Local Variables declared within a function definition private to a function definition variables in different functions are totally independent different functions can have variables with the same names; however, each variable will have its own memory address * * * *

int x = 3; // global because before main void main(void) { // no variables local to main( ) void myfunction( ); // prototype cout <<"x = "<<x<<" before the function call.\n"; myfunction( ); cout <<"x = "<<x<<" after the function call.\n"; } void myfunction( ) { int r; // local to myfunction( ) r = ++x; cout <<"r = "<<r<<" within the function.\n";

Scope OUTPUT x = 3 before the function call. r = 4 within the function. x = 4 after the function call.

Example - ReadValues void main(void) { int a, b, c; float avg; 1. 2. 3. 4. 5. 6. 7. 8. 9. void main(void) { int a, b, c; float avg; void ReadValues( int&, int&, int& ); void Adjust( int&, int&, int& ); float Average( int, int, int ); void WriteResults( int, int, int, int, float ); ReadValues(a, b, c); Adjust(a, b, c); avg = Average(a, b, c); WriteResults(a, b, c, a + b + c, avg); }

Example - ReadValues 1. main declares and calls ReadValues 2. ReadValues declares and calls ReadOne [3x] 3. main declares and calls Adjust 4. main declares and calls Average 5. main declares and calls WriteResults * * * *

Example - ReadValues * * void ReadValues( /* */ int& x, /* */ int& y, /* */ int& z ) { void ReadOne( char, int& ); ReadOne('1', x ); ReadOne('2', y ); ReadOne('3', z ); return; } out out * *

Example - ReadOne void ReadOne( /* */ char number, /* */ int& item ) { cout << "Enter value " << number << ": "; cin >> item; return; } in out * *

Example - Adjust * * void Adjust( /* */ int& i, /* */ int& j, inout /* */ int& k ) { int smallest; smallest = i; if (j < smallest) i = i - smallest; smallest = j; j = j - smallest; if (k < smallest) k = k - smallest; smallest = k; return; } inout inout * *

Example - Average * * float Average( /* */ int item1, /* */ int item2, { int total; total = item1 + item2 + item3; return float(total) / 3; } in in * *

Example - WriteResults void WriteResults( /* */ int item1, /* */ int item2, /* */ int item3, /* */ int total, /* */ float average ) { cout << "Adjusted values: " << item1 << ", " << item2 << ", " << item3 << '\n' << "Sum: " << total << " Average: " << average << '\n'; return; } in in * *

Main ReadValues Adjust Average WriteResults ReadOne Enter value 1: 23 Adjusted values: 0, 33, 55 Sum: 88 Average: 29.3333

void swap(int, int); // a global function void main(void) { int x = 5, y = 10; 1. cout <<“Main-before swap, x: “<<x<<" y: "<<y<< '\n'; swap(x, y); 2. cout <<"Main-after swap, x: "<<x<<" y: "<<y<<'\n'; } void swap(int x, int y) { int temp; 3. cout <<"Swap-before swap, x: "<<x<<" y: "<<y<<'\n'; temp = x; x = y; y = temp; 4. cout <<"Swap-after swap, x: "<<x<<" y: "<<y<<'\n';

Scope OUTPUT 1. Main-before swap: x: 5 y: 10 3. Swap-before swap: x: 5 y: 10 4. Swap-after swap: x: 10 y: 5 2. Main-after swap: x: 5 y: 10

Scope within a Block void Block1(int, char &); void Block2( ); int a1; // global char a2; // global int main() { . . . } slide 1 of 2

. . . . . . void Block1(int a1, char &b2) // prevents access { // to global a1 int c1; // local to Block1 int d1; // local to Block1 } . . . void Block2() { int a1; // prevents access to global a1 int b1; // local to Block2 while (…) { // Block3 int c1; // local to Block3 int b2; // prevents non-local access } // to b2 in Block1 . . . slide 2 of 2 *

Scope within a block - Ex. 1 predict the output void scope2(void); // function prototype void main(void) { int v=100; cout <<"v BEFORE function = "<<v<<'\n'; scope2(); cout <<"v AFTER function = "<<v<<'\n'; } slide 1 of 2

Scope within a block - Ex. 1 predict the output 1. void scope2(void) //function header 2. { double v = 5.5; 3. int k, j; 4. cout << "v outside block = " << v<<'\n'; 5. for (k=1; k<=3; k++) 6. { int v = 17; // initialized in function 7. for (j=1; j<=2; j++) 8. { v++; 9. cout << "v inside block = " << v<<'\n'; 10. } 11. } 12. cout << "v outside block = " << v<<'\n'; 13. } slide 2 of 2

Scope within a block - Ex. 2 void scope2(void); // function prototype void main(void) { int v=100; cout <<"v BEFORE function = "<<v<<'\n'; scope2(); cout <<"v AFTER function = "<<v<<'\n'; } slide 1 of 2

Scope within a block - Ex. 2 1. void scope2(void) //function header 2. { double v = 5.5; 3. int k, j; 4. cout << "v outside block = " << v <<'\n'; 5. for (k=1; k<=3; k++) 6. { int v = 17; // initialized in function 7. for (j=1; j<=2; j++) 8. { v ++; 9. cout << "v inside block = " << v <<'\n'; 10. } 11. } 12. cout << "v outside block = " << v <<'\n'; } slide 2 of 2

} } Scope within a block j loops k loop * OUTPUT 100 BEFORE 5.5 outside 18 inside 19 inside 5.5 outside 100 AFTER } k loop j loops } *

Global Resolution Operator :: double rougon = 999.99; // global void main(void) { double rougon = 12.3; // local cout<< rougon << “ = rougon, local\n” cout<< ::rougon << “ = rougon, global\n”; } OUTPUT 12.3 = rougon, local 999.99 = rougon, global * *

Variable Storage Classes Local auto static register ý while (l l l) { int k = 1; k++; l l l } while (l l l) { static int k = 1; k++; l l l } * * *

Variable Storage Classes Global static extern ý

Scope & Storage Classes - an example int x = 1; // global variable main() { int x = 5; // local variable to main cout << "local x in outer scope of main is " << x << endl; { // start new scope int x = 7; cout << "local x in inner scope of main is " <<x<< endl; } // end new scope from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example (continued) a(); // a has automatic local x b(); // b has static local x c(); // c uses global x a(); // a reinitializes automatic local x b(); // static local x retains its previous value c(); // global x also retains its value cout << "local x in main is " << x << endl; return 0; } // end of main() from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example void a(void) { int x = 25; // initialized each time a is called cout << endl << "local x in a is " << x << " after entering a" << endl; ++x; cout << "local x in a is " << x << " before exiting a" << endl; } from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example void b(void) { static int x = 50; // Static initialization only // first time b is called cout << endl << "local static x is " << x << " on entering b" << endl; ++x; cout << "local static x is " << x << " on exiting b" << endl; } from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example void c(void) { cout << endl << "global x is " << x << " on entering c" << endl; x *= 10; cout << "global x is " << x << " on exiting c" << endl; } from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example b(); c(); a(); // a has automatic local x b(); // b has static local x c(); // c uses global x a(); // a reinitializes automatic local x b(); // static local x retains its previous value c(); // global x also retains its value from Deitel & Deitel 1e, fig 3.12 *

Scope & Storage Classes - an example OUTPUT local x in outer scope of main is 5 local x in inner scope of main is 7 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5 from Deitel & Deitel 1e, fig 3.12

Scope & Storage Classes - an example void a(void) { int x = 25; // initialized each time a is called cout << endl << "local x in a is " << x << " after entering a" << endl; ++x; cout << "local x in a is " << x << " before exiting a" << endl; } from Deitel & Deitel 1e, fig 3.12 << ‘\t’ << ::x << endl; *

Common Errors Passing incorrect data types Using the same variable name for different variables ex. local - in both the calling and called functions global - must use ::

Common Errors Wrong positioning of the called function prototype Terminating a function header with a ; Forgetting the data type of a function’s parameter

Debugging char = junk; and cin << junk; Prevention - plan first! Valuation tables Display values Use Find or Replace for == vs. = C++ Debugger

“Heavier-than-air flying machines are impossible.” Lord Kelvin, End Note 1 “Heavier-than-air flying machines are impossible.” Lord Kelvin, President of the Royal Society, 1895

End Note 2 “If A = success, then the formula is A = X + Y + Z. X is work. Y is play. Z is keep your mouth shut.” Albert Einstein