Computer Science 1620 Function Scope & Global Variables.

Slides:



Advertisements
Similar presentations
Pass by Value. COMP104 Pass by Value / Slide 2 Passing Parameters by Value * A function returns a single result (assuming the function is not a void function)
Advertisements

Computer Science 1620 Function Overloading. Review Question: suppose I have the following function: can I call this function with an integer? yes – compiler.
Chapter 6 Advanced Function Features Pass by Value Pass by Reference Const parameters Overloaded functions.
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.
Local and Global Variables. COMP104 Local and Global / Slide 2 Scope The scope of a declaration is the block of code where the identifier is valid for.
Chapter 5 Functions.
Computer Science 1620 Default Parameter Values. Default Parameters If a projectile is launched vertically with velocity v 0, the maximum height it will.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Programming Scope of Identifiers. COMP102 Prog. Fundamentals I: Scope of Identifiers/ Slide 2 Scope l A sequence of statements within { … } is considered.
Computer Science 1620 Other Data Types. Quick Review: checklist for performing user input: 1) Be sure variable is declared 2) Prompt the user for input.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Computer Science 1620 Arrays. Problem: Given a list of 5 student grades, adjust the grades so that the average is 70%. Program design: 1. read in the.
Local, Global Variables, and Scope. COMP104 Slide 2 Functions are ‘global’, variables are ‘local’ int main() { int x,y,z; … } int one(int x, …) { double.
Methods of variable creation Global variable –declared very early stage –available at all times from anywhere –created at the start of the program, and.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Computer Science 1620 Lifetime & Scope. Variable Lifetime a variable's lifetime is finite Variable creation: memory is allocated to the variable occurs.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
1 Chapter 9 Scope, Lifetime, and More on Functions.
Functions g g Data Flow g Scope local global part 4 part 4.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Scope Accessibility of Names. Review We’ve seen that C++ permits a programmer to declare names and then use those names in a manner consistent with their.
CSC 107 – Programming For Science. Today’s Goal  Discuss writing & using functions  How to declare them, use them, & trace them  Could write programs.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
February 11, 2005 More Pointers Dynamic Memory Allocation.
Variable Scope Storage Class Recursion
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
C++ Basics C++ is a high-level, general purpose, object-oriented programming language.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 11 Functions – Part III By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 Cannon_Chapter9 Strings and the string Class. 2 Overview  Standards for Strings  String Declarations and Assignment  I/O with string Variables 
Engineering Problem Solving with C++, Second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 5 Parameter Passing 11/06/13.
#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.
1 More Operator Overloading Chapter Objectives You will be able to: Define and use an overloaded operator to output objects of your own classes.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions Parameters passed by reference.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Function 2. User-Defined Functions C++ programs usually have the following form: // include statements // function prototypes // main() function // function.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
3. The Nuts and Bolts of C++ Computer Programming 3. The Nuts and Bolts of C++ 1 Learning the C++ language 3. The Nuts and Bolts of C++ 16 September 2008.
Cop3530sp12. Parameter passing call by value- appropriate for small objects that should not be altered by the function call by constant reference- appropriate.
Introduction to Programming Lecture 6. Functions – Call by value – Call by reference Today's Lecture Includes.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
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.
Advanced Programming in C
Functions Scope local global Global Resolution Operator part 5.
ㅎㅎ Fourth step for Learning C++ Programming Namespace Function
Bill Tucker Austin Community College COSC 1315
A Lecture for the c++ Course
Pointers and Pointer-Based Strings
Global & Local Identifiers
Chapter 9 Scope, Lifetime, and More on Functions
FUNCTIONS& FUNCTIONS OVERLOADING
Screen output // Definition and use of variables
Counting Loops.
Namespaces How Shall I Name Thee?.
Local, Global Variables, and Scope
Pointers and Pointer-Based Strings
CS 144 Advanced C++ Programming January 31 Class Meeting
FOR statement a compact notation for a WHILE e.g. sumgrades = 0;
Presentation transcript:

Computer Science 1620 Function Scope & Global Variables

Functions and Scope recall that a variable's scope does not extend past the statement block in which it is defined therefore, a variable declared in a function can only be used in that function this also applies to parameter variables

#include using namespace std; double factorial(int x) { double result = 1; for (int y = 1; y <= x; y++) result *= y; return result; } int main() { cout << "Factorial of 5 = " << factorial(5) << endl; cout << "Result of computation = " << result << endl; return 0; } Variable result's lifetime Compiler error: result is being used outside of its scope.

#include using namespace std; double factorial(int x) { double result = 1; for (int y = 1; y <= x; y++) result *= y; return result; } int main() { cout << "Factorial of 5 = " << factorial(5) << endl; cout << "Result of computation = " << x << endl; return 0; } Variable x's lifetime Compiler error: x is being used outside of its scope.

Functions and Scope since a variable's scope doesn't exist past the function it is declared in, two functions can have the same variable name refers to two different variables

#include using namespace std; double factorial(int n) { double result = 1; for (int y = 1; y <= n; y++) result *= y; return result; } int choose(int n, int r) { double result = factorial(n) / (factorial(r) * factorial(n-r)); return static_cast (result); } int main() { cout << "5 choose 2 = " << choose(5, 2) << endl; return 0; } These variables are distinct, even though they have the same name.

Global Variables all variables so far have been declared within a function local variables also called automatic variables what happens if a variable is declared outside of a function variable becomes global its scope is any function defined after its declaration its lifetime is until the end of the program

#include using namespace std; double result; double factorial(int x) { result = 1.0; for (int y = 1; y <= x; y++) result *= y; return result; } int main() { cout << "Factorial of 5 = " << factorial(5) << endl; cout << "Result of computation = " << result << endl; return 0; } Variable result's lifetime This is ok; result is being used within its scope.

#include using namespace std; double factorial(int x) { result = 1.0; for (int y = 1; y <= x; y++) result *= y; return result; } double result; int main() { cout << "Factorial of 5 = " << factorial(5) << endl; cout << "Result of computation = " << result << endl; return 0; } Variable result's lifetime Compiler error: result being used outside of its scope

Global Variables & Name Resolution suppose you have a global variable and local variable with the same name which variable takes priority? int a = 1; int main() { int a = 2; cout << "a = " << a << endl; return 0; } Does this output a 1 or a 2?

Global Variables & Name Resolution Rule: local variables hide global variables with the same name int a = 1; int main() { int a = 2; cout << "a = " << a << endl; return 0; } This outputs a 2

Global Variables & Name Resolution Rule: local variables hide global variables with the same name local variables hide global variables until they go out of scope int a = 1; int main() { int a = 2; cout << "a = " << a << endl; return 0; } This outputs a 2

Global Variables & Name Resolution Rule: local variables hide global variables with the same name local variables hide global variables until they go out of scope int a = 1; int main() { { int a = 2; } cout << "a = " << a << endl; return 0; } This outputs a 1

Scope Operator unlike a local variable that's hidden, there is a way to acquire the value of a hidden global variable use the scope operator (::) int a = 1; int main() { int a = 2; cout << "a = " << a << endl; return 0; } This outputs a 2

Scope Operator unlike a local variable that's hidden, there is a way to acquire the value of a hidden global variable use the scope operator (::) tells C++ to look for variable in global space int a = 1; int main() { int a = 1; cout << "a = " << ::a << endl; return 0; } This outputs a 1

Global Variables vs. Parameters since global variables exist across functions, they can be used to pass information from function to function instead of using parameters and return types, just use global variables NOT RECOMMENDED

#include using namespace std; double factorial(int x) { double result = 1; for (int y = 1; y <= x; y++) result *= y; return result; } int main() { cout << "Factorial of 5 = " << factorial(5) << endl; return 0; }

#include using namespace std; int x; double result; void factorial() { result = 1.0; for (int y = 1; y <= x; y++) result *= y; } int main() { x = 5; factorial(); cout << "Factorial of 5 = " << result << endl; return 0; }

Global Variables vs. Parameters using global variables for parameter passing and return values is considered bad programming practice difficult to follow risk of overwriting parameters or return values risk of hiding global variable sometimes leads to longer code

#include using namespace std; int x; double result; void factorial() { result = 1.0; for (int y = 1; y <= x; y++) result *= y; } int main() { x = 5; factorial(); cout << "Factorial of 5 = " << result << endl; return 0; } No obvious associativity with function call

#include using namespace std; double factorial(int x) { double result = 1; for (int y = 1; y <= x; y++) result *= y; return result; } int main() { cout << "5 choose 2 = " << factorial(5)/ (factorial(2) * factorial(5-2)) << endl; return 0; }

#include using namespace std; int x; double result; void factorial() { result = 1.0; for (int y = 1; y <= x; y++) result *= y; } int main() { cout << "5 choose 2 = "; double choose = 1.0; x = 5; factorial(); choose *= result; x = 2; factorial(); choose /= result; x = 3; factorial(); choose /= result; cout << "5 choose 2 = " << choose << endl; return 0; }

Global Variables what are global values used for? named constants named constants are very often declared outside of a function, rather than inside of a function this way, all the functions can use the named constant external variables to be discussed later (if at all)

Write a program that reads the radius of a sphere, and outputs its widest circumference, its volume, and its surface area #include using namespace std; int main() { const double PI = 3.14; double r; cout << "Please enter the radius of the sphere (m): "; cin >> r; cout << "Circumference (m): " << 2 * PI * r << endl; cout << "Volume (m^3): " << 4.0 / 3.0 *PI*r*r*r <<endl; cout << "Surface Area (m^2): " << 4 * PI * r*r << endl; return 0; }

Write a program that reads the radius of a sphere, and outputs its widest circumference, its volume, and its surface area #include using namespace std; const double PI = 3.14; int main() { double r; cout << "Please enter the radius of the sphere (m): "; cin >> r; cout << "Circumference (m): " << 2 * PI * r << endl; cout << "Volume (m^3): " << 4.0 / 3.0 *PI*r*r*r <<endl; cout << "Surface Area (m^2): " << 4 * PI * r*r << endl; return 0; }