SlideShare a Scribd company logo
1 of 21
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

What's hot

Function in c++
Function in c++Function in c++
Function in c++Kumar
 
Type conversions
Type conversionsType conversions
Type conversionssanya6900
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Jenish Patel
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Java 8 Functional Programming - I
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - IUgur Yeter
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_cForwardBlog Enewzletter
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++Vraj Patel
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Learn By Watch
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming javaManeesh Chaturvedi
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macrosAnand Kumar
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default argumentsNikhil Pandit
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional ProgrammingSartaj Singh
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programmingAssaf Gannon
 
Functions and tasks in verilog
Functions and tasks in verilogFunctions and tasks in verilog
Functions and tasks in verilogNallapati Anindra
 
Introduction to programming using mat ab
Introduction to programming using mat abIntroduction to programming using mat ab
Introduction to programming using mat abAhmed Hisham
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#Ali Hassan
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialKuntal Bhowmick
 

What's hot (20)

Function in c++
Function in c++Function in c++
Function in c++
 
Type conversions
Type conversionsType conversions
Type conversions
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Java 8 Functional Programming - I
Java 8 Functional Programming - IJava 8 Functional Programming - I
Java 8 Functional Programming - I
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
05 functional programming
05 functional programming05 functional programming
05 functional programming
 
INLINE FUNCTION IN C++
INLINE FUNCTION IN C++INLINE FUNCTION IN C++
INLINE FUNCTION IN C++
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
Functional programming java
Functional programming javaFunctional programming java
Functional programming java
 
Inline function
Inline functionInline function
Inline function
 
Inline functions & macros
Inline functions & macrosInline functions & macros
Inline functions & macros
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Basics of Functional Programming
Basics of Functional ProgrammingBasics of Functional Programming
Basics of Functional Programming
 
Intro to functional programming
Intro to functional programmingIntro to functional programming
Intro to functional programming
 
Functions and tasks in verilog
Functions and tasks in verilogFunctions and tasks in verilog
Functions and tasks in verilog
 
Introduction to programming using mat ab
Introduction to programming using mat abIntroduction to programming using mat ab
Introduction to programming using mat ab
 
Command Line Arguments in C#
Command Line Arguments in C#Command Line Arguments in C#
Command Line Arguments in C#
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
 

Similar to CPP07 - Scope

Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptAmanuelZewdie4
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionBlue Elephant Consulting
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptxVAIBHAVKADAGANCHI
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++Mukund Trivedi
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slidesluqman bawany
 
C language
C languageC language
C languageRobo India
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingestorebackupr
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptxmiki304759
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structureSelf-Employed
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptxTKSanthoshRao
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Rasan Samarasinghe
 

Similar to CPP07 - Scope (20)

Chapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.pptChapter Introduction to Modular Programming.ppt
Chapter Introduction to Modular Programming.ppt
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
 
Intro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, RecursionIntro To C++ - Class #20: Functions, Recursion
Intro To C++ - Class #20: Functions, Recursion
 
Functions
FunctionsFunctions
Functions
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Introduction to C ++.pptx
Introduction to C ++.pptxIntroduction to C ++.pptx
Introduction to C ++.pptx
 
Functions
FunctionsFunctions
Functions
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
Introduction to c first week slides
Introduction to c first week slidesIntroduction to c first week slides
Introduction to c first week slides
 
Python functions
Python functionsPython functions
Python functions
 
Functions
FunctionsFunctions
Functions
 
C language
C languageC language
C language
 
Function in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programmingFunction in C++, Methods in C++ coding programming
Function in C++, Methods in C++ coding programming
 
Chapter One Function.pptx
Chapter One Function.pptxChapter One Function.pptx
Chapter One Function.pptx
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Algorithm and C code related to data structure
Algorithm and C code related to data structureAlgorithm and C code related to data structure
Algorithm and C code related to data structure
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 
Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++Esoft Metro Campus - Programming with C++
Esoft Metro Campus - Programming with C++
 

More from Michael Heron

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMichael Heron
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconductMichael Heron
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkMichael Heron
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility SupportMichael Heron
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and AutershipMichael Heron
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interactionMichael Heron
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - InheritanceMichael Heron
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityMichael Heron
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - TexturesMichael Heron
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - ShadingMichael Heron
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)Michael Heron
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)Michael Heron
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationMichael Heron
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsMichael Heron
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsMichael Heron
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationMichael Heron
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IOMichael Heron
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - TemplatesMichael Heron
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - AbstractionMichael Heron
 

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Recently uploaded

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

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.