Handout # 4 functions + scopes

NUST Stuff

c++ http://nustweb.blogspot.com/

LAB # 11 HANDOUT
Objectives:
Overloaded Functions:
Overloaded functions help us to have multiple functions with the same name but with different
arguments/parameter list. This allows for better readability of the code: multiple functions having self-
evident names can be defined which take input arguments of different data types. It can also help if we
mistakenly pass wrong/different arguments to the function.
While defining overloaded functions, the thing that needs to be different is the data type of the parameter
list. The return data type may or may not be changed accordingly.
Practice Questions:
1. Write three averaging functions (for 4 numbers) with the same name but with int, float and double data
type of input argument respectively.
2. Write 3 overloaded calculator functions (for int, float and double) that take character as one of the
parameters and depending upon this parameter performs the basic 4 mathematical functions (+, -, *, /).
3. Write two overloaded functions that convert float into int and vice versa. (Hint: If the user enters 5.6, the
function should return 5 and if the user enters 4, the function should return 4.0.)
Pass By Value vs Pass By Reference:
Up until now, we have been passing the arguments to a function by value. What that means is that a copy is
created of the variables passed to the function and all the manipulation is done on that copy. This means that
there is no effect on the original value of the variable.
There is another way of passing the value of a variable to a function. That method is called pass by reference.
The syntax for doing so is as follows:
void my_function (int &my_variable);
The ampersand (&) makes it possible to pass the function by reference. It sends the address of the variable
to the function. As the changes are happening to the original value, therefore there is no need for a return value
hence the use of void.
In the main, there aren’t any changes when calling a function that takes a reference to a variable as an input
argument.
Practice Questions:
Repeat the tasks listed above but this time, pass all the values by reference.
Scope Rules and Variables:
In C++, a scope is defined by { }. Just like nested loops and nested if/else, scopes can exist inside other scopes.
The variables defined in one scope may or may not be visible/accessible inside other scopes. Scope allow us
to have same named variables even in different scopes.
{ //Outer Scope
{ //Inner Scope}
}
{ int x = 0;
{ int y = 1;
cout<<x<<endl<<y;}
}
As soon as we exit a scope, the values of the variables in that scope are destroyed. What this means is that
whenever we return from a function call, the values of the variables declared and initialized in that function
(or temporary variables) aren’t saved anymore.
Global and Static Variables:
Global variables are such variables which are visible to all the scopes in a program. These variables can be
used/updated from anywhere and can be used when there needs to be a single value visible everywhere. Any
variable that is defined and initialized above main ( ) becomes a global variable.
Variables can be made static by using the keyword static. This ensures that the value of the variable is kept
safe even after we have exited the scope. In other words, when we want to have static value between function
calls, we can make a variable static. So, no matter when that particular function is called, the value of the
particular static variable will remain the same.
Practice Questions:
1. Write a function that “remembers” how many times it has been called.
2. Declare two variables both name X. One of these variables should be accessible from anywhere. While
the other one should only be accessible from main.
3. In the above task, display the value of X declared above main in main. (Hint: Use the Unary operator :: ).
4. Re-write an averaging function for 4 numbers that only uses global variables.
5. Re-write the calculator function using global variables.

Recomendados

Java script function por
Java script functionJava script function
Java script functionsuresh raj sharma
57 visualizações17 slides
Operators used in vb.net por
Operators used in vb.netOperators used in vb.net
Operators used in vb.netJaya Kumari
304 visualizações15 slides
Function Parameters por
Function ParametersFunction Parameters
Function Parametersprimeteacher32
625 visualizações10 slides
Python Built-in Functions and Use cases por
Python Built-in Functions and Use casesPython Built-in Functions and Use cases
Python Built-in Functions and Use casesSrajan Mor
359 visualizações12 slides
Type conversions por
Type conversionsType conversions
Type conversionssanya6900
7.7K visualizações12 slides
Python functions part12 por
Python functions  part12Python functions  part12
Python functions part12Vishal Dutt
56 visualizações10 slides

Mais conteúdo relacionado

Mais procurados

Books por
BooksBooks
BooksSteven Foster Murray
140 visualizações14 slides
Functions por
FunctionsFunctions
FunctionsSepti Ratnasari
287 visualizações34 slides
Mule expression por
Mule expressionMule expression
Mule expressionRavinder Singh
396 visualizações10 slides
Introduction To Programming with Python Lecture 2 por
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Syed Farjad Zia Zaidi
1.2K visualizações20 slides
Operators in java By cheena por
Operators in java By cheenaOperators in java By cheena
Operators in java By cheenaChëëñå Båbü
16 visualizações29 slides
FUNCTION CPU por
FUNCTION CPUFUNCTION CPU
FUNCTION CPUKrushal Kakadia
1.3K visualizações19 slides

Mais procurados(20)

Functions por Septi Ratnasari
FunctionsFunctions
Functions
Septi Ratnasari287 visualizações
Mule expression por Ravinder Singh
Mule expressionMule expression
Mule expression
Ravinder Singh396 visualizações
Introduction To Programming with Python Lecture 2 por Syed Farjad Zia Zaidi
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
Syed Farjad Zia Zaidi1.2K visualizações
Operators in java By cheena por Chëëñå Båbü
Operators in java By cheenaOperators in java By cheena
Operators in java By cheena
Chëëñå Båbü16 visualizações
FUNCTION CPU por Krushal Kakadia
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
Krushal Kakadia1.3K visualizações
Function por Saniati
FunctionFunction
Function
Saniati 111 visualizações
Sorting two numbers por devil00dante
Sorting two numbersSorting two numbers
Sorting two numbers
devil00dante95 visualizações
Notes: Verilog Part 5 - Tasks and Functions por Jay Baxi
Notes: Verilog Part 5 - Tasks and FunctionsNotes: Verilog Part 5 - Tasks and Functions
Notes: Verilog Part 5 - Tasks and Functions
Jay Baxi1.5K visualizações
Compiler: Programming Language= Assignments and statements por Geo Marian
Compiler: Programming Language= Assignments and statementsCompiler: Programming Language= Assignments and statements
Compiler: Programming Language= Assignments and statements
Geo Marian1.3K visualizações
Operators in java por AbhishekMondal42
Operators in javaOperators in java
Operators in java
AbhishekMondal42237 visualizações
Handout # 3 functions c++ por NUST Stuff
Handout # 3   functions c++Handout # 3   functions c++
Handout # 3 functions c++
NUST Stuff82 visualizações
Functions and tasks in verilog por Nallapati Anindra
Functions and tasks in verilogFunctions and tasks in verilog
Functions and tasks in verilog
Nallapati Anindra2.6K visualizações
Introduction To Programming with Python-1 por Syed Farjad Zia Zaidi
Introduction To Programming with Python-1Introduction To Programming with Python-1
Introduction To Programming with Python-1
Syed Farjad Zia Zaidi1.2K visualizações
Functions in python slide share por Devashish Kumar
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar21.6K visualizações
Demystifying Eta Expansion por Knoldus Inc.
Demystifying Eta ExpansionDemystifying Eta Expansion
Demystifying Eta Expansion
Knoldus Inc.237 visualizações
User Defined Functions in C por RAJ KUMAR
User Defined Functions in CUser Defined Functions in C
User Defined Functions in C
RAJ KUMAR78 visualizações
C programming language working with functions 1 por Jeevan Raj
C programming language working with functions 1C programming language working with functions 1
C programming language working with functions 1
Jeevan Raj150 visualizações
Function in C++ por Prof Ansari
Function in C++Function in C++
Function in C++
Prof Ansari154 visualizações

Destaque

Drg 4ab mv por
Drg 4ab mvDrg 4ab mv
Drg 4ab mvNUST Stuff
47 visualizações2 slides
Drg 2 geometry por
Drg 2 geometryDrg 2 geometry
Drg 2 geometryNUST Stuff
59 visualizações1 slide
2559 project por
2559 project 2559 project
2559 project Kantapon Knight
132 visualizações4 slides
International.doc (2) por
International.doc (2)International.doc (2)
International.doc (2)egwakhe happiness
178 visualizações13 slides
Mohammad Mahdi Arab Farsi Resume por
Mohammad Mahdi Arab Farsi ResumeMohammad Mahdi Arab Farsi Resume
Mohammad Mahdi Arab Farsi ResumeMohammad Mahdi Arab
300 visualizações33 slides
Волонтёрское движение как форма социализации школьников por
Волонтёрское движение как форма социализации школьниковВолонтёрское движение как форма социализации школьников
Волонтёрское движение как форма социализации школьниковАндрей Мирошниченко
251 visualizações21 slides

Destaque(16)

Drg 4ab mv por NUST Stuff
Drg 4ab mvDrg 4ab mv
Drg 4ab mv
NUST Stuff47 visualizações
Drg 2 geometry por NUST Stuff
Drg 2 geometryDrg 2 geometry
Drg 2 geometry
NUST Stuff59 visualizações
2559 project por Kantapon Knight
2559 project 2559 project
2559 project
Kantapon Knight132 visualizações
International.doc (2) por egwakhe happiness
International.doc (2)International.doc (2)
International.doc (2)
egwakhe happiness178 visualizações
Mohammad Mahdi Arab Farsi Resume por Mohammad Mahdi Arab
Mohammad Mahdi Arab Farsi ResumeMohammad Mahdi Arab Farsi Resume
Mohammad Mahdi Arab Farsi Resume
Mohammad Mahdi Arab300 visualizações
Волонтёрское движение как форма социализации школьников por Андрей Мирошниченко
Волонтёрское движение как форма социализации школьниковВолонтёрское движение как форма социализации школьников
Волонтёрское движение как форма социализации школьников
Assignment # 3 computer system and Programming EC-105 por NUST Stuff
Assignment # 3   computer system and Programming EC-105 Assignment # 3   computer system and Programming EC-105
Assignment # 3 computer system and Programming EC-105
NUST Stuff106 visualizações
Assignment # 2 computer system and Programming EC-105 por NUST Stuff
Assignment # 2   computer system and Programming EC-105 Assignment # 2   computer system and Programming EC-105
Assignment # 2 computer system and Programming EC-105
NUST Stuff161 visualizações
Виставка дитячих робіт por Alexey Musienko
Виставка дитячих робітВиставка дитячих робіт
Виставка дитячих робіт
Alexey Musienko117 visualizações
Accreditation and licensing por NUST Stuff
Accreditation and licensingAccreditation and licensing
Accreditation and licensing
NUST Stuff401 visualizações
Storage container for japan market por leo tan
Storage container for japan marketStorage container for japan market
Storage container for japan market
leo tan116 visualizações
Flat pack japan fukushima-disaster site por leo tan
Flat pack   japan fukushima-disaster siteFlat pack   japan fukushima-disaster site
Flat pack japan fukushima-disaster site
leo tan122 visualizações
Introduction to Programming and QBasic Tutorial por nhomz
Introduction to Programming and QBasic TutorialIntroduction to Programming and QBasic Tutorial
Introduction to Programming and QBasic Tutorial
nhomz3.6K visualizações
Consumption as part of Aggregate Demand por mattbentley34
Consumption as part of Aggregate DemandConsumption as part of Aggregate Demand
Consumption as part of Aggregate Demand
mattbentley34578 visualizações
Handout # 6 pointers and recursion in c++ por NUST Stuff
Handout # 6   pointers and recursion in c++Handout # 6   pointers and recursion in c++
Handout # 6 pointers and recursion in c++
NUST Stuff303 visualizações
Long run aggregate_supply por mattbentley34
Long run aggregate_supplyLong run aggregate_supply
Long run aggregate_supply
mattbentley341.1K visualizações

Similar a Handout # 4 functions + scopes

04. WORKING WITH FUNCTIONS-2 (1).pptx por
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptxManas40552
13 visualizações77 slides
Introduction to c programming por
Introduction to c programmingIntroduction to c programming
Introduction to c programmingAMAN ANAND
101 visualizações22 slides
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) por
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)Mansi Tyagi
4.2K visualizações21 slides
1669958779195.pdf por
1669958779195.pdf1669958779195.pdf
1669958779195.pdfvenud11
11 visualizações13 slides
User defined function in C.pptx por
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
2 visualizações57 slides
Userdefined functions brief explaination.pdf por
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfDeeptiMalhotra19
4 visualizações18 slides

Similar a Handout # 4 functions + scopes (20)

04. WORKING WITH FUNCTIONS-2 (1).pptx por Manas40552
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas4055213 visualizações
Introduction to c programming por AMAN ANAND
Introduction to c programmingIntroduction to c programming
Introduction to c programming
AMAN ANAND101 visualizações
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) por Mansi Tyagi
 FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM) FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
FUNCTION IN C PROGRAMMING UNIT -6 (BCA I SEM)
Mansi Tyagi4.2K visualizações
1669958779195.pdf por venud11
1669958779195.pdf1669958779195.pdf
1669958779195.pdf
venud1111 visualizações
User defined function in C.pptx por Rhishav Poudyal
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal2 visualizações
Userdefined functions brief explaination.pdf por DeeptiMalhotra19
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
DeeptiMalhotra194 visualizações
Amit user defined functions xi (2) por Arpit Meena
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
Arpit Meena110 visualizações
GUI Programming in JAVA (Using Netbeans) - A Review por Fernando Torres
GUI Programming in JAVA (Using Netbeans) -  A ReviewGUI Programming in JAVA (Using Netbeans) -  A Review
GUI Programming in JAVA (Using Netbeans) - A Review
Fernando Torres7.3K visualizações
Functions in C++.pdf por LadallaRajKumar
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
LadallaRajKumar36 visualizações
Functions-Computer programming por nmahi96
Functions-Computer programmingFunctions-Computer programming
Functions-Computer programming
nmahi9682 visualizações
Chapter 11 Function por Deepak Singh
Chapter 11 FunctionChapter 11 Function
Chapter 11 Function
Deepak Singh319 visualizações
User Defined Functions por praveenjigajinni
User Defined FunctionsUser Defined Functions
User Defined Functions
praveenjigajinni2.3K visualizações
Arrays &amp; functions in php por Ashish Chamoli
Arrays &amp; functions in phpArrays &amp; functions in php
Arrays &amp; functions in php
Ashish Chamoli558 visualizações
Functions in c language por Tanmay Modi
Functions in c languageFunctions in c language
Functions in c language
Tanmay Modi606 visualizações
Functions in c language por tanmaymodi4
Functions in c language Functions in c language
Functions in c language
tanmaymodi42.7K visualizações
Classes function overloading por ankush_kumar
Classes function overloadingClasses function overloading
Classes function overloading
ankush_kumar1.9K visualizações
Functions-.pdf por arvdexamsection
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection2 visualizações
4. function por Shankar Gangaju
4. function4. function
4. function
Shankar Gangaju511 visualizações

Mais de NUST Stuff

Me211 1 por
Me211 1Me211 1
Me211 1NUST Stuff
1K visualizações14 slides
Lab LCA 1 7 por
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7NUST Stuff
1.8K visualizações48 slides
Me211 2 por
Me211 2Me211 2
Me211 2NUST Stuff
1.7K visualizações26 slides
Me211 4 por
Me211 4Me211 4
Me211 4NUST Stuff
154 visualizações1 slide
Me211 3 por
Me211 3Me211 3
Me211 3NUST Stuff
621 visualizações4 slides
Drag force on a sphere in yield stress fluid por
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluidNUST Stuff
214 visualizações3 slides

Mais de NUST Stuff(20)

Me211 1 por NUST Stuff
Me211 1Me211 1
Me211 1
NUST Stuff1K visualizações
Lab LCA 1 7 por NUST Stuff
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7
NUST Stuff1.8K visualizações
Me211 2 por NUST Stuff
Me211 2Me211 2
Me211 2
NUST Stuff1.7K visualizações
Me211 4 por NUST Stuff
Me211 4Me211 4
Me211 4
NUST Stuff154 visualizações
Me211 3 por NUST Stuff
Me211 3Me211 3
Me211 3
NUST Stuff621 visualizações
Drag force on a sphere in yield stress fluid por NUST Stuff
Drag force on a sphere in yield stress fluidDrag force on a sphere in yield stress fluid
Drag force on a sphere in yield stress fluid
NUST Stuff214 visualizações
Nums entry test 2017 paper por NUST Stuff
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paper
NUST Stuff13K visualizações
Nums entry-test-new-syllabus-mbbsc-bds por NUST Stuff
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bds
NUST Stuff515 visualizações
MCAT Full length paper 8-student_copy_ por NUST Stuff
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_
NUST Stuff1.1K visualizações
MCAT Full length paper 7-student_copy_ por NUST Stuff
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_
NUST Stuff515 visualizações
MCAT Full length paper 6-student_copy_ por NUST Stuff
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_
NUST Stuff628 visualizações
MCAT Full length paper 5-student_copy_ por NUST Stuff
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_
NUST Stuff788 visualizações
Mcat (original paper 2014) por NUST Stuff
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)
NUST Stuff917 visualizações
MCAT Full length paper 4-student_copy por NUST Stuff
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copy
NUST Stuff578 visualizações
mcat (original paper 2013) por NUST Stuff
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)
NUST Stuff1.1K visualizações
mcat (original paper 2012) por NUST Stuff
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)
NUST Stuff482 visualizações
MCAT Full length paper 3 final por NUST Stuff
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 final
NUST Stuff168 visualizações
MCAT (original paper 2011) por NUST Stuff
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)
NUST Stuff356 visualizações
MCAT Full length paper 2 (student copy) por NUST Stuff
MCAT Full length paper  2 (student copy)MCAT Full length paper  2 (student copy)
MCAT Full length paper 2 (student copy)
NUST Stuff375 visualizações
mcat (original paper 2010) por NUST Stuff
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)
NUST Stuff447 visualizações

Último

STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf por
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfSTRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfDr Vijay Vishwakarma
130 visualizações68 slides
Collective Bargaining and Understanding a Teacher Contract(16793704.1).pptx por
Collective Bargaining and Understanding a Teacher Contract(16793704.1).pptxCollective Bargaining and Understanding a Teacher Contract(16793704.1).pptx
Collective Bargaining and Understanding a Teacher Contract(16793704.1).pptxCenter for Integrated Training & Education
106 visualizações57 slides
Papal.pdf por
Papal.pdfPapal.pdf
Papal.pdfMariaKenney3
68 visualizações24 slides
Java Simplified: Understanding Programming Basics por
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsAkshaj Vadakkath Joshy
653 visualizações155 slides
Class 9 lesson plans por
Class 9 lesson plansClass 9 lesson plans
Class 9 lesson plansTARIQ KHAN
82 visualizações34 slides
BUSINESS ETHICS MODULE 1 UNIT I_A.pdf por
BUSINESS ETHICS MODULE 1 UNIT I_A.pdfBUSINESS ETHICS MODULE 1 UNIT I_A.pdf
BUSINESS ETHICS MODULE 1 UNIT I_A.pdfDr Vijay Vishwakarma
40 visualizações25 slides

Último(20)

STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf por Dr Vijay Vishwakarma
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdfSTRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
STRATEGIC MANAGEMENT MODULE 1_UNIT1 _UNIT2.pdf
Dr Vijay Vishwakarma130 visualizações
Papal.pdf por MariaKenney3
Papal.pdfPapal.pdf
Papal.pdf
MariaKenney368 visualizações
Java Simplified: Understanding Programming Basics por Akshaj Vadakkath Joshy
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
Akshaj Vadakkath Joshy653 visualizações
Class 9 lesson plans por TARIQ KHAN
Class 9 lesson plansClass 9 lesson plans
Class 9 lesson plans
TARIQ KHAN82 visualizações
BUSINESS ETHICS MODULE 1 UNIT I_A.pdf por Dr Vijay Vishwakarma
BUSINESS ETHICS MODULE 1 UNIT I_A.pdfBUSINESS ETHICS MODULE 1 UNIT I_A.pdf
BUSINESS ETHICS MODULE 1 UNIT I_A.pdf
Dr Vijay Vishwakarma40 visualizações
MercerJesse3.0.pdf por jessemercerail
MercerJesse3.0.pdfMercerJesse3.0.pdf
MercerJesse3.0.pdf
jessemercerail152 visualizações
Guess Papers ADC 1, Karachi University por Khalid Aziz
Guess Papers ADC 1, Karachi UniversityGuess Papers ADC 1, Karachi University
Guess Papers ADC 1, Karachi University
Khalid Aziz99 visualizações
Monthly Information Session for MV Asterix (November) por Esquimalt MFRC
Monthly Information Session for MV Asterix (November)Monthly Information Session for MV Asterix (November)
Monthly Information Session for MV Asterix (November)
Esquimalt MFRC107 visualizações
Meet the Bible por Steve Thomason
Meet the BibleMeet the Bible
Meet the Bible
Steve Thomason78 visualizações
EILO EXCURSION PROGRAMME 2023 por info33492
EILO EXCURSION PROGRAMME 2023EILO EXCURSION PROGRAMME 2023
EILO EXCURSION PROGRAMME 2023
info33492202 visualizações
NodeJS and ExpressJS.pdf por ArthyR3
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
ArthyR348 visualizações
ANGULARJS.pdf por ArthyR3
ANGULARJS.pdfANGULARJS.pdf
ANGULARJS.pdf
ArthyR351 visualizações
CUNY IT Picciano.pptx por apicciano
CUNY IT Picciano.pptxCUNY IT Picciano.pptx
CUNY IT Picciano.pptx
apicciano64 visualizações
Narration lesson plan por TARIQ KHAN
Narration lesson planNarration lesson plan
Narration lesson plan
TARIQ KHAN75 visualizações
Education of marginalized and socially disadvantages segments.pptx por GarimaBhati5
Education of marginalized and socially disadvantages segments.pptxEducation of marginalized and socially disadvantages segments.pptx
Education of marginalized and socially disadvantages segments.pptx
GarimaBhati543 visualizações
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice por Taste
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a ChoiceCreative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Creative Restart 2023: Atila Martins - Craft: A Necessity, Not a Choice
Taste45 visualizações
UNIDAD 3 6º C.MEDIO.pptx por MarcosRodriguezUcedo
UNIDAD 3 6º C.MEDIO.pptxUNIDAD 3 6º C.MEDIO.pptx
UNIDAD 3 6º C.MEDIO.pptx
MarcosRodriguezUcedo146 visualizações

Handout # 4 functions + scopes

  • 1. LAB # 11 HANDOUT Objectives: Overloaded Functions: Overloaded functions help us to have multiple functions with the same name but with different arguments/parameter list. This allows for better readability of the code: multiple functions having self- evident names can be defined which take input arguments of different data types. It can also help if we mistakenly pass wrong/different arguments to the function. While defining overloaded functions, the thing that needs to be different is the data type of the parameter list. The return data type may or may not be changed accordingly. Practice Questions: 1. Write three averaging functions (for 4 numbers) with the same name but with int, float and double data type of input argument respectively. 2. Write 3 overloaded calculator functions (for int, float and double) that take character as one of the parameters and depending upon this parameter performs the basic 4 mathematical functions (+, -, *, /). 3. Write two overloaded functions that convert float into int and vice versa. (Hint: If the user enters 5.6, the function should return 5 and if the user enters 4, the function should return 4.0.) Pass By Value vs Pass By Reference: Up until now, we have been passing the arguments to a function by value. What that means is that a copy is created of the variables passed to the function and all the manipulation is done on that copy. This means that there is no effect on the original value of the variable. There is another way of passing the value of a variable to a function. That method is called pass by reference. The syntax for doing so is as follows: void my_function (int &my_variable); The ampersand (&) makes it possible to pass the function by reference. It sends the address of the variable to the function. As the changes are happening to the original value, therefore there is no need for a return value hence the use of void. In the main, there aren’t any changes when calling a function that takes a reference to a variable as an input argument. Practice Questions: Repeat the tasks listed above but this time, pass all the values by reference.
  • 2. Scope Rules and Variables: In C++, a scope is defined by { }. Just like nested loops and nested if/else, scopes can exist inside other scopes. The variables defined in one scope may or may not be visible/accessible inside other scopes. Scope allow us to have same named variables even in different scopes. { //Outer Scope { //Inner Scope} } { int x = 0; { int y = 1; cout<<x<<endl<<y;} } As soon as we exit a scope, the values of the variables in that scope are destroyed. What this means is that whenever we return from a function call, the values of the variables declared and initialized in that function (or temporary variables) aren’t saved anymore. Global and Static Variables: Global variables are such variables which are visible to all the scopes in a program. These variables can be used/updated from anywhere and can be used when there needs to be a single value visible everywhere. Any variable that is defined and initialized above main ( ) becomes a global variable. Variables can be made static by using the keyword static. This ensures that the value of the variable is kept safe even after we have exited the scope. In other words, when we want to have static value between function calls, we can make a variable static. So, no matter when that particular function is called, the value of the particular static variable will remain the same. Practice Questions: 1. Write a function that “remembers” how many times it has been called. 2. Declare two variables both name X. One of these variables should be accessible from anywhere. While the other one should only be accessible from main. 3. In the above task, display the value of X declared above main in main. (Hint: Use the Unary operator :: ). 4. Re-write an averaging function for 4 numbers that only uses global variables. 5. Re-write the calculator function using global variables.