SlideShare a Scribd company logo
Scope
Michael Heron
Introduction
• Having discussed the idea of functions, we can now move on
to one of the consequences.
• The idea of variable scope.
• Scope is what defines the lifetime of a variable.
• Variables have a life-cycle which they follow.
• Scope determines their life-span.
• This has particular importance for functions and when we talk
about pointers in the next lecture.
Scope
#include <iostream>
using namespace std;
int add_nums (int x, int y) {
int answer;
answer = x + y;
return answer;
}
int main() {
add_nums (10, 20);
cout << answer << endl;
return 1;
}
Scope
• This program will not compile.
• It will complain about variables not being defined as being in
scope.
• Variables that are defined within a function are accessible
only within that function.
• They cannot be accessed in other functions.
• Variables defined in functions are known as local variables.
• They are local to a particular function.
Scope
• There is a process that the compiler will go through when
creating a variable.
• We touched on this in an earlier lecture.
• First of all, a declaration of a variable is an instruction for the
compiler.
• It says to the compiler ‘Set aside some space in memory for me,
big enough to hold something of this type’
• When we define a local variable, it goes to a particular
location in memory.
• The stack
Local Variables
• When a function has finished executing, the variables are
removed from the stack.
• They no longer exist, in a very real sense.
• We don’t need to do this ourselves.
• C++ handles it for us.
• If we try to make use of that variable in another function,
we’re making use of a variable that no longer exists in
memory.
• Hence the complaints.
Global Variables
• This contrasts to the idea of a global variable.
• This is a variable that is available throughout an entire program.
• It exists in memory as long as the program is running.
• Global variables are declared outside the bounds of any
function in a C++ program.
• Usually at the top of the file.
Global Variables
#include <iostream>
using namespace std;
int answer;
int add_nums (int x, int y) {
answer = x + y;
return answer;
}
int main() {
add_nums (10, 20);
cout << answer << endl;
return 1;
}
Global Variables
• This program will work quite happily.
• Answer is a variable available to both functions.
• We can have as many global variables as we like.
• Well, within reason…
• Global variables remain in memory until the application has
finished executing.
Global Variables – The Good
• Global variables are obviously very convenient.
• No need to worry about declaring variables all the time.
• They can increase efficiency in some restricted situations.
• They make your programs go faster.
• None of these situations will present themselves during this
module.
Global Variables – The Bad
• In general, avoid global variables.
• They lead to code that is unnecessarily difficult to read.
• They are non-local and thus prone to manipulation outside of the
functions in which they are used.
• They create unexpected side-effects.
• They continue to consume memory after they have become
useless.
• They reduce the reusability of your code.
Local Variables – Learn To Love
Them
• Local variables avoid all of these problems.
• They are destroyed when they are no longer in use, saving
memory.
• They cannot be accessed out of their context.
• They are visible in the function in which they are defined.
• You can reuse the functions directly.
• Where possible, make use of local variables only.
Loop Scoping
• We can restrict the scope even further by declaring counter
variables directly into a for loop.
• Their scope exists only as long as the loop is executing.
• This is a syntactic nicety rather than anything else:
for (int i = 0; i < 100; i++) {
cout << i << endl;
}
Arrays as Parameters
• We talked about arrays before we talked about functions.
• And thus we never touched upon the syntax for passing arrays to
functions.
• The parameters you send into your functions are local
variables.
• They just get their initial value set external to the function.
• They have the same scoping issues.
Arrays as Parameters
• When we pass an array to a function in C++, we must include
the brackets.
• One set of brackets to indicate dimensionality.
• We often need to pass the size of an array into the function
also.
• The issue of scope means that whatever mechanism we are using
to track the size of our array will be local to the function in which
it is located.
Arrays as Parameters
int main() {
int nums[10];
int size = 0;
int input;
do {
cin >> input;
if (input != -1) {
nums[size] = input;
size += 1;
}
} while (input != -1 & size < 10);
cout << sum_numbers (nums, size)
<< endl;
}
int sum_numbers (int nums[], int size)
{
int total;
for (int i = 0; i < size; i++) {
total += nums[i];
}
return total;
}
Function Overloading
• The last thing we are going to talk about today is the idea of
function overloading.
• Not especially related to the day’s topic, but an aside.
• Functions in C++ are not uniquely identified by their name
alone.
• They are identified by their name, and the type and order of
their parameters.
• This is known as the function signature.
Function Overloading
• We can provide multiple methods with the same name in a
program, as long as we have different parameter lists.
• This is important for designing good programs.
• We don’t need:
• add_two_ints
• add_two_floats
• We provide overloaded methods
Function Overloading
#include <iostream>
using namespace std;
int answer;
int add_nums (int x, int y) {
return x + y;
}
float add_nums (float x, float y) {
return x + y;
}
int main() {
cout << add_nums (1, 2) << endl;
cout << add_nums (1.2f, 3.1f) << endl;
return 1;
}
Function Overloading
• When the compiler compiles our program, it works out which
of those methods it is going to execute by examining the
provided parameters.
• It executes the matching function only.
• In cases where there is ambiguity, it will give a compile time
error.
• In the program we saw, we need to tell c++ we are working with
floats using the 1.2f notation.
Summary
• Variables have scope.
• This is their ‘expected lifetime’
• They are either local scope
• Defined in a function
• Or global scope
• Defined outside a function.
• We can overload methods.
• To give us more consistent naming.

More Related Content

PPTX
Function in C Programming
Anil Pokhrel
 
PPTX
2CPP18 - Modifiers
Michael Heron
 
PPTX
Function
Saniati
 
PPT
Basics of cpp
vinay chauhan
 
PPTX
CPP06 - Functions
Michael Heron
 
PPTX
Lecture 4: Functions
Vivek Bhargav
 
PPTX
XII Computer Science- Chapter 1-Function
Prem Joel
 
PDF
Functional programming 101
Maneesh Chaturvedi
 
Function in C Programming
Anil Pokhrel
 
2CPP18 - Modifiers
Michael Heron
 
Function
Saniati
 
Basics of cpp
vinay chauhan
 
CPP06 - Functions
Michael Heron
 
Lecture 4: Functions
Vivek Bhargav
 
XII Computer Science- Chapter 1-Function
Prem Joel
 
Functional programming 101
Maneesh Chaturvedi
 

What's hot (20)

PPTX
Function in c++
Kumar
 
PPT
Type conversions
sanya6900
 
PPTX
Inline function in C++
Jenish Patel
 
PDF
Intro to functional programming
Assaf Gannon
 
PPTX
Functions in Python
Shakti Singh Rathore
 
PPTX
Java 8 Functional Programming - I
Ugur Yeter
 
PPTX
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
PPTX
05 functional programming
Victor Matyushevskyy
 
PPTX
INLINE FUNCTION IN C++
Vraj Patel
 
PPTX
Inline function in C++
Learn By Watch
 
PDF
Functional programming java
Maneesh Chaturvedi
 
PPTX
Inline function
Tech_MX
 
PPTX
Inline functions & macros
Anand Kumar
 
PPTX
Inline Functions and Default arguments
Nikhil Pandit
 
PDF
Basics of Functional Programming
Sartaj Singh
 
PDF
Intro to functional programming
Assaf Gannon
 
PDF
Functions and tasks in verilog
Nallapati Anindra
 
PPTX
Introduction to programming using mat ab
Ahmed Hisham
 
PPTX
Command Line Arguments in C#
Ali Hassan
 
PDF
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
Function in c++
Kumar
 
Type conversions
sanya6900
 
Inline function in C++
Jenish Patel
 
Intro to functional programming
Assaf Gannon
 
Functions in Python
Shakti Singh Rathore
 
Java 8 Functional Programming - I
Ugur Yeter
 
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
05 functional programming
Victor Matyushevskyy
 
INLINE FUNCTION IN C++
Vraj Patel
 
Inline function in C++
Learn By Watch
 
Functional programming java
Maneesh Chaturvedi
 
Inline function
Tech_MX
 
Inline functions & macros
Anand Kumar
 
Inline Functions and Default arguments
Nikhil Pandit
 
Basics of Functional Programming
Sartaj Singh
 
Intro to functional programming
Assaf Gannon
 
Functions and tasks in verilog
Nallapati Anindra
 
Introduction to programming using mat ab
Ahmed Hisham
 
Command Line Arguments in C#
Ali Hassan
 
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
Ad

Similar to CPP07 - Scope (20)

PPT
Functions in c++
Abdullah Turkistani
 
PPTX
Operator Overloading and Scope of Variable
MOHIT DADU
 
PPT
02 functions, variables, basic input and output of c++
Manzoor ALam
 
PPT
Function overloading(c++)
Ritika Sharma
 
PPT
Function overloading(C++)
Ritika Sharma
 
PPT
Function oveloading
Ritika Sharma
 
PPT
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
PPT
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
sekemioxiel
 
PDF
Chapter 11 Function
Deepak Singh
 
PPTX
C++ Functions
Jari Abbas
 
PDF
Function in C++
Prof Ansari
 
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
iczzzyjaz9646
 
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
zeltuprvth360
 
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
lablegtaton
 
PPTX
Functions in C++ programming language.pptx
rebin5725
 
PPTX
C++ Overview PPT
Thooyavan Venkatachalam
 
PDF
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
qsvaevu455
 
PPTX
c++ introduction, array, pointers included.pptx
fn723290
 
Functions in c++
Abdullah Turkistani
 
Operator Overloading and Scope of Variable
MOHIT DADU
 
02 functions, variables, basic input and output of c++
Manzoor ALam
 
Function overloading(c++)
Ritika Sharma
 
Function overloading(C++)
Ritika Sharma
 
Function oveloading
Ritika Sharma
 
chapterintroductiontomodularprogramming-230112092330-e3eb5a74 (1).ppt
harinipradeep15
 
Chapter Introduction to Modular Programming.ppt
AmanuelZewdie4
 
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
sekemioxiel
 
Chapter 11 Function
Deepak Singh
 
C++ Functions
Jari Abbas
 
Function in C++
Prof Ansari
 
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
iczzzyjaz9646
 
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
zeltuprvth360
 
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
lablegtaton
 
Functions in C++ programming language.pptx
rebin5725
 
C++ Overview PPT
Thooyavan Venkatachalam
 
Starting Out With C++ From Control Structures To Objects 9th Edition Gaddis S...
qsvaevu455
 
c++ introduction, array, pointers included.pptx
fn723290
 
Ad

More from Michael Heron (20)

PPTX
Meeple centred design - Board Game Accessibility
Michael Heron
 
PPTX
Musings on misconduct
Michael Heron
 
PDF
Accessibility Support with the ACCESS Framework
Michael Heron
 
PDF
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
PPTX
Authorship and Autership
Michael Heron
 
PDF
Text parser based interaction
Michael Heron
 
PPTX
SAD04 - Inheritance
Michael Heron
 
PPT
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
PPT
GRPHICS07 - Textures
Michael Heron
 
PPT
GRPHICS06 - Shading
Michael Heron
 
PPT
GRPHICS05 - Rendering (2)
Michael Heron
 
PPT
GRPHICS04 - Rendering (1)
Michael Heron
 
PPTX
GRPHICS03 - Graphical Representation
Michael Heron
 
PPTX
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
PPTX
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
PPT
GRPHICS09 - Art Appreciation
Michael Heron
 
PPTX
2CPP17 - File IO
Michael Heron
 
PPT
2CPP16 - STL
Michael Heron
 
PPT
2CPP15 - Templates
Michael Heron
 
PPTX
2CPP14 - Abstraction
Michael Heron
 
Meeple centred design - Board Game Accessibility
Michael Heron
 
Musings on misconduct
Michael Heron
 
Accessibility Support with the ACCESS Framework
Michael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
Michael Heron
 
Authorship and Autership
Michael Heron
 
Text parser based interaction
Michael Heron
 
SAD04 - Inheritance
Michael Heron
 
GRPHICS08 - Raytracing and Radiosity
Michael Heron
 
GRPHICS07 - Textures
Michael Heron
 
GRPHICS06 - Shading
Michael Heron
 
GRPHICS05 - Rendering (2)
Michael Heron
 
GRPHICS04 - Rendering (1)
Michael Heron
 
GRPHICS03 - Graphical Representation
Michael Heron
 
GRPHICS02 - Creating 3D Graphics
Michael Heron
 
GRPHICS01 - Introduction to 3D Graphics
Michael Heron
 
GRPHICS09 - Art Appreciation
Michael Heron
 
2CPP17 - File IO
Michael Heron
 
2CPP16 - STL
Michael Heron
 
2CPP15 - Templates
Michael Heron
 
2CPP14 - Abstraction
Michael Heron
 

Recently uploaded (20)

PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PPTX
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
PDF
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PDF
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
TRAVEL APIs | WHITE LABEL TRAVEL API | TOP TRAVEL APIs
philipnathen82
 
Balancing Resource Capacity and Workloads with OnePlan – Avoid Overloading Te...
OnePlan Solutions
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
WatchTraderHub - Watch Dealer software with inventory management and multi-ch...
WatchDealer Pavel
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Activate_Methodology_Summary presentatio
annapureddyn
 

CPP07 - Scope

  • 2. Introduction • Having discussed the idea of functions, we can now move on to one of the consequences. • The idea of variable scope. • Scope is what defines the lifetime of a variable. • Variables have a life-cycle which they follow. • Scope determines their life-span. • This has particular importance for functions and when we talk about pointers in the next lecture.
  • 3. Scope #include <iostream> using namespace std; int add_nums (int x, int y) { int answer; answer = x + y; return answer; } int main() { add_nums (10, 20); cout << answer << endl; return 1; }
  • 4. Scope • This program will not compile. • It will complain about variables not being defined as being in scope. • Variables that are defined within a function are accessible only within that function. • They cannot be accessed in other functions. • Variables defined in functions are known as local variables. • They are local to a particular function.
  • 5. Scope • There is a process that the compiler will go through when creating a variable. • We touched on this in an earlier lecture. • First of all, a declaration of a variable is an instruction for the compiler. • It says to the compiler ‘Set aside some space in memory for me, big enough to hold something of this type’ • When we define a local variable, it goes to a particular location in memory. • The stack
  • 6. Local Variables • When a function has finished executing, the variables are removed from the stack. • They no longer exist, in a very real sense. • We don’t need to do this ourselves. • C++ handles it for us. • If we try to make use of that variable in another function, we’re making use of a variable that no longer exists in memory. • Hence the complaints.
  • 7. Global Variables • This contrasts to the idea of a global variable. • This is a variable that is available throughout an entire program. • It exists in memory as long as the program is running. • Global variables are declared outside the bounds of any function in a C++ program. • Usually at the top of the file.
  • 8. Global Variables #include <iostream> using namespace std; int answer; int add_nums (int x, int y) { answer = x + y; return answer; } int main() { add_nums (10, 20); cout << answer << endl; return 1; }
  • 9. Global Variables • This program will work quite happily. • Answer is a variable available to both functions. • We can have as many global variables as we like. • Well, within reason… • Global variables remain in memory until the application has finished executing.
  • 10. Global Variables – The Good • Global variables are obviously very convenient. • No need to worry about declaring variables all the time. • They can increase efficiency in some restricted situations. • They make your programs go faster. • None of these situations will present themselves during this module.
  • 11. Global Variables – The Bad • In general, avoid global variables. • They lead to code that is unnecessarily difficult to read. • They are non-local and thus prone to manipulation outside of the functions in which they are used. • They create unexpected side-effects. • They continue to consume memory after they have become useless. • They reduce the reusability of your code.
  • 12. Local Variables – Learn To Love Them • Local variables avoid all of these problems. • They are destroyed when they are no longer in use, saving memory. • They cannot be accessed out of their context. • They are visible in the function in which they are defined. • You can reuse the functions directly. • Where possible, make use of local variables only.
  • 13. Loop Scoping • We can restrict the scope even further by declaring counter variables directly into a for loop. • Their scope exists only as long as the loop is executing. • This is a syntactic nicety rather than anything else: for (int i = 0; i < 100; i++) { cout << i << endl; }
  • 14. Arrays as Parameters • We talked about arrays before we talked about functions. • And thus we never touched upon the syntax for passing arrays to functions. • The parameters you send into your functions are local variables. • They just get their initial value set external to the function. • They have the same scoping issues.
  • 15. Arrays as Parameters • When we pass an array to a function in C++, we must include the brackets. • One set of brackets to indicate dimensionality. • We often need to pass the size of an array into the function also. • The issue of scope means that whatever mechanism we are using to track the size of our array will be local to the function in which it is located.
  • 16. Arrays as Parameters int main() { int nums[10]; int size = 0; int input; do { cin >> input; if (input != -1) { nums[size] = input; size += 1; } } while (input != -1 & size < 10); cout << sum_numbers (nums, size) << endl; } int sum_numbers (int nums[], int size) { int total; for (int i = 0; i < size; i++) { total += nums[i]; } return total; }
  • 17. Function Overloading • The last thing we are going to talk about today is the idea of function overloading. • Not especially related to the day’s topic, but an aside. • Functions in C++ are not uniquely identified by their name alone. • They are identified by their name, and the type and order of their parameters. • This is known as the function signature.
  • 18. Function Overloading • We can provide multiple methods with the same name in a program, as long as we have different parameter lists. • This is important for designing good programs. • We don’t need: • add_two_ints • add_two_floats • We provide overloaded methods
  • 19. Function Overloading #include <iostream> using namespace std; int answer; int add_nums (int x, int y) { return x + y; } float add_nums (float x, float y) { return x + y; } int main() { cout << add_nums (1, 2) << endl; cout << add_nums (1.2f, 3.1f) << endl; return 1; }
  • 20. Function Overloading • When the compiler compiles our program, it works out which of those methods it is going to execute by examining the provided parameters. • It executes the matching function only. • In cases where there is ambiguity, it will give a compile time error. • In the program we saw, we need to tell c++ we are working with floats using the 1.2f notation.
  • 21. Summary • Variables have scope. • This is their ‘expected lifetime’ • They are either local scope • Defined in a function • Or global scope • Defined outside a function. • We can overload methods. • To give us more consistent naming.