SlideShare a Scribd company logo
1 of 16
EC-102 Computer System &
Programming
Lecture #6
Instructor: Jahan Zeb
Department of Computer Engineering (DCE)
College of E&ME
References and Reference Parameters
 Call by value
– Copy of data passed to function
– Changes to copy do not change original
– Prevent unwanted side effects
 Call by reference
– Function can directly access data
– Changes affect original
Reference Parameters
 Reference parameter
– Alias for argument in function call
• Passes parameter by reference
– Use & after data type in prototype
• void myFunction( int &data )
• Read “data is a reference to an int”
– Function call format the same
• However, original can now be changed
1 // Fig. 3.20: fig03_20.cpp
2 // Comparing pass-by-value and pass-by-reference
3 // with references.
4 #include <iostream>
5
6 using std::cout;
7 using std::endl;
8
9 int squareByValue( int ); // function prototype
10 void squareByReference( int & ); // function prototype
11
12 int main()
13 {
14 int x = 2;
15 int z = 4;
16
17 // demonstrate squareByValue
18 cout << "x = " << x << " before squareByValuen";
19 cout << "Value returned by squareByValue: "
20 << squareByValue( x ) << endl;
21 cout << "x = " << x << " after squareByValuen" << endl;
22
Notice the & operator,
indicating pass-by-reference.
23 // demonstrate squareByReference
24 cout << "z = " << z << " before squareByReference" << endl;
25 squareByReference( z );
26 cout << "z = " << z << " after squareByReference" << endl;
27
28 return 0; // indicates successful termination
29 } // end main
30
31 // squareByValue multiplies number by itself, stores the
32 // result in number and returns the new value of number
33 int squareByValue( int number )
34 {
35 return number *= number; // caller's argument not modified
36
37 } // end function squareByValue
38
39 // squareByReference multiplies numberRef by itself and
40 // stores the result in the variable to which numberRef
41 // refers in function main
42 void squareByReference( int &numberRef )
43 {
44 numberRef *= numberRef; // caller's argument modified
45
46 } // end function squareByReference
Changes number, but
original parameter (x) is not
modified.
Changes numberRef, an
alias for the original
parameter. Thus, z is
changed.
x = 2 before squareByValue
Value returned by squareByValue: 4
x = 2 after squareByValue
 
z = 4 before squareByReference
z = 16 after squareByReference
References and Reference Parameters
References as aliases to other variables
– Refer to same variable
– Can be used within a function
int count = 1; // declare integer variable count
Int &cRef = count; // create cRef as an alias for count
++cRef; // increment count (using its alias)
 References must be initialized when declared
– Otherwise, compiler error
– Dangling reference
• Reference to undefined variable
1 // Fig. 3.21: fig03_21.cpp
2 // References must be initialized.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int x = 3;
11
12 // y refers to (is an alias for) x
13 int &y = x;
14
15 cout << "x = " << x << endl << "y = " << y << endl;
16 y = 7;
17 cout << "x = " << x << endl << "y = " << y << endl;
18
19 return 0; // indicates successful termination
20
21 } // end main
x = 3
y = 3
x = 7
y = 7
y declared as a reference to x.
1 // Fig. 3.22: fig03_22.cpp
2 // References must be initialized.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int x = 3;
11 int &y; // Error: y must be initialized
12
13 cout << "x = " << x << endl << "y = " << y << endl;
14 y = 7;
15 cout << "x = " << x << endl << "y = " << y << endl;
16
17 return 0; // indicates successful termination
18
19 } // end main
'y' : references must be initialized
Uninitialized reference –
compiler error.
Default Arguments
 Function call with omitted parameters
– If not enough parameters, rightmost go to their defaults
– Default values
• Can be constants, global variables, or function calls
 Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
– myFunction(3)
• x = 3, y and z get defaults (rightmost)
– myFunction(3, 5)
• x = 3, y = 5 and z gets default
1 // Fig. 3.23: fig03_23.cpp
2 // Using default arguments.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function prototype that specifies default arguments
9 int boxVolume( int length = 1, int width = 1, int height = 1 );
10
11 int main()
12 {
13 // no arguments--use default values for all dimensions
14 cout << "The default box volume is: " << boxVolume();
15
16 // specify length; default width and height
17 cout << "nnThe volume of a box with length 10,n"
18 << "width 1 and height 1 is: " << boxVolume( 10 );
19
20 // specify length and width; default height
21 cout << "nnThe volume of a box with length 10,n"
22 << "width 5 and height 1 is: " << boxVolume( 10, 5 );
23
Set defaults in function
prototype.
Function calls with some
parameters missing – the
rightmost parameters get their
defaults.
24 // specify all arguments
25 cout << "nnThe volume of a box with length 10,n"
26 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 )
27 << endl;
28
29 return 0; // indicates successful termination
30
31 } // end main
32
33 // function boxVolume calculates the volume of a box
34 int boxVolume( int length, int width, int height )
35 {
36 return length * width * height;
37
38 } // end function boxVolume
The default box volume is: 1
 
The volume of a box with length 10,
width 1 and height 1 is: 10
 
The volume of a box with length 10,
width 5 and height 1 is: 50
 
The volume of a box with length 10,
width 5 and height 2 is: 100
Unary Scope Resolution Operator
 Unary scope resolution operator (::)
– Access global variable if local variable has same name
– Not needed if names are different
– Use ::variable
• y = ::x + 3;
– Good to avoid using same names for locals and globals
Function Overloading
 Function overloading
– Functions with same name and different parameters
– Should perform similar tasks
• I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }
 Overloaded functions distinguished by signature
– Based on name and parameter types (order matters)
– Name mangling
• Encodes function identifier with parameters
– Type-safe linkage
• Ensures proper overloaded function called
1 // Fig. 3.25: fig03_25.cpp
2 // Using overloaded functions.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 // function square for int values
9 int square( int x )
10 {
11 cout << "Called square with int argument: " << x << endl;
12 return x * x;
13
14 } // end int version of function square
15
16 // function square for double values
17 double square( double y )
18 {
19 cout << "Called square with double argument: " << y << endl;
20 return y * y;
21
22 } // end double version of function square
23
Overloaded functions have
the same name, but the
different parameters
distinguish them.
24 int main()
25 {
26 int intResult = square( 7 ); // calls int version
27 double doubleResult = square( 7.5 ); // calls double version
28
29 cout << "nThe square of integer 7 is " << intResult
30 << "nThe square of double 7.5 is " << doubleResult
31 << endl;
32
33 return 0; // indicates successful termination
34
35 } // end main
Called square with int argument: 7
Called square with double argument: 7.5
 
The square of integer 7 is 49
The square of double 7.5 is 56.25
The proper function is called
based upon the argument
(int or double).

More Related Content

What's hot

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++NUST Stuff
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3Ali Aminian
 
Types of function call
Types of function callTypes of function call
Types of function callArijitDhali
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT03062679929
 
Function in c++
Function in c++Function in c++
Function in c++Kumar
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIADheeraj Kataria
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#khush_boo31
 
PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSArpee Callejo
 

What's hot (20)

16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Function C++
Function C++ Function C++
Function C++
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++Lecture#8 introduction to array with examples c++
Lecture#8 introduction to array with examples c++
 
Learning C++ - Functions in C++ 3
Learning C++ - Functions  in C++ 3Learning C++ - Functions  in C++ 3
Learning C++ - Functions in C++ 3
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Types of function call
Types of function callTypes of function call
Types of function call
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
Function in c++
Function in c++Function in c++
Function in c++
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in C
Functions in CFunctions in C
Functions in C
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
 
Recursion in c++
Recursion in c++Recursion in c++
Recursion in c++
 
Function
FunctionFunction
Function
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
PARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMSPARAMETER PASSING MECHANISMS
PARAMETER PASSING MECHANISMS
 

Viewers also liked

Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language CourseVivek chan
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programsharman kaur
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.pptTareq Hasan
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming LanguageAhmad Idrees
 

Viewers also liked (10)

Complete C++ programming Language Course
Complete C++ programming Language CourseComplete C++ programming Language Course
Complete C++ programming Language Course
 
Unit 6 pointers
Unit 6   pointersUnit 6   pointers
Unit 6 pointers
 
Intro to C++ - language
Intro to C++ - languageIntro to C++ - language
Intro to C++ - language
 
Basic c++ programs
Basic c++ programsBasic c++ programs
Basic c++ programs
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
01 c++ Intro.ppt
01 c++ Intro.ppt01 c++ Intro.ppt
01 c++ Intro.ppt
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
C++ ppt
C++ pptC++ ppt
C++ ppt
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
 

Similar to Lecture#7 Call by value and reference in c++

Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionstemkin abdlkader
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Abdul Samee
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxDeepasCSE
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2Warui Maina
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxGebruGetachew2
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxShashiShash2
 
how to reuse code
how to reuse codehow to reuse code
how to reuse codejleed1
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 

Similar to Lecture#7 Call by value and reference in c++ (20)

Dd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functionsDd3.15 thru-3.21-advanced-functions
Dd3.15 thru-3.21-advanced-functions
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01Part 3-functions1-120315220356-phpapp01
Part 3-functions1-120315220356-phpapp01
 
C++ Functions.ppt
C++ Functions.pptC++ Functions.ppt
C++ Functions.ppt
 
FUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptxFUNCTIONS, CLASSES AND OBJECTS.pptx
FUNCTIONS, CLASSES AND OBJECTS.pptx
 
Functions in C++.pdf
Functions in C++.pdfFunctions in C++.pdf
Functions in C++.pdf
 
functions
functionsfunctions
functions
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
06
0606
06
 
2.overview of c++ ________lecture2
2.overview of c++  ________lecture22.overview of c++  ________lecture2
2.overview of c++ ________lecture2
 
CHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptxCHAPTER THREE FUNCTION.pptx
CHAPTER THREE FUNCTION.pptx
 
Intro to c++
Intro to c++Intro to c++
Intro to c++
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
C++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptxC++ FUNCTIONS-1.pptx
C++ FUNCTIONS-1.pptx
 
how to reuse code
how to reuse codehow to reuse code
how to reuse code
 
functions
functionsfunctions
functions
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
4th unit full
4th unit full4th unit full
4th unit full
 

More from NUST Stuff

Drag force on a sphere in yield stress fluid
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
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paperNUST Stuff
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNUST Stuff
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_NUST Stuff
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_NUST Stuff
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_NUST Stuff
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_NUST Stuff
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)NUST Stuff
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copyNUST Stuff
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)NUST Stuff
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)NUST Stuff
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 finalNUST Stuff
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)NUST Stuff
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)NUST Stuff
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)NUST Stuff
 

More from NUST Stuff (20)

Me211 1
Me211 1Me211 1
Me211 1
 
Lab LCA 1 7
Lab LCA 1 7Lab LCA 1 7
Lab LCA 1 7
 
Me211 2
Me211 2Me211 2
Me211 2
 
Me211 4
Me211 4Me211 4
Me211 4
 
Me211 3
Me211 3Me211 3
Me211 3
 
Drag force on a sphere in yield stress fluid
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
 
Nums entry test 2017 paper
Nums entry test 2017 paperNums entry test 2017 paper
Nums entry test 2017 paper
 
Nums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bdsNums entry-test-new-syllabus-mbbsc-bds
Nums entry-test-new-syllabus-mbbsc-bds
 
MCAT Full length paper 8-student_copy_
MCAT Full length paper  8-student_copy_MCAT Full length paper  8-student_copy_
MCAT Full length paper 8-student_copy_
 
MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_MCAT Full length paper 7-student_copy_
MCAT Full length paper 7-student_copy_
 
MCAT Full length paper 6-student_copy_
MCAT Full length paper  6-student_copy_MCAT Full length paper  6-student_copy_
MCAT Full length paper 6-student_copy_
 
MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_MCAT Full length paper 5-student_copy_
MCAT Full length paper 5-student_copy_
 
Mcat (original paper 2014)
Mcat (original paper 2014)Mcat (original paper 2014)
Mcat (original paper 2014)
 
MCAT Full length paper 4-student_copy
MCAT Full length paper  4-student_copyMCAT Full length paper  4-student_copy
MCAT Full length paper 4-student_copy
 
mcat (original paper 2013)
mcat (original paper 2013)mcat (original paper 2013)
mcat (original paper 2013)
 
mcat (original paper 2012)
mcat (original paper 2012)mcat (original paper 2012)
mcat (original paper 2012)
 
MCAT Full length paper 3 final
MCAT Full length paper 3 finalMCAT Full length paper 3 final
MCAT Full length paper 3 final
 
MCAT (original paper 2011)
MCAT (original paper 2011)MCAT (original paper 2011)
MCAT (original paper 2011)
 
mcat (original paper 2010)
 mcat (original paper 2010) mcat (original paper 2010)
mcat (original paper 2010)
 
MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)MCAT Full length paper 1 (student copy)
MCAT Full length paper 1 (student copy)
 

Recently uploaded

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

Lecture#7 Call by value and reference in c++

  • 1. EC-102 Computer System & Programming Lecture #6 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME
  • 2. References and Reference Parameters  Call by value – Copy of data passed to function – Changes to copy do not change original – Prevent unwanted side effects  Call by reference – Function can directly access data – Changes affect original
  • 3. Reference Parameters  Reference parameter – Alias for argument in function call • Passes parameter by reference – Use & after data type in prototype • void myFunction( int &data ) • Read “data is a reference to an int” – Function call format the same • However, original can now be changed
  • 4. 1 // Fig. 3.20: fig03_20.cpp 2 // Comparing pass-by-value and pass-by-reference 3 // with references. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 int squareByValue( int ); // function prototype 10 void squareByReference( int & ); // function prototype 11 12 int main() 13 { 14 int x = 2; 15 int z = 4; 16 17 // demonstrate squareByValue 18 cout << "x = " << x << " before squareByValuen"; 19 cout << "Value returned by squareByValue: " 20 << squareByValue( x ) << endl; 21 cout << "x = " << x << " after squareByValuen" << endl; 22 Notice the & operator, indicating pass-by-reference.
  • 5. 23 // demonstrate squareByReference 24 cout << "z = " << z << " before squareByReference" << endl; 25 squareByReference( z ); 26 cout << "z = " << z << " after squareByReference" << endl; 27 28 return 0; // indicates successful termination 29 } // end main 30 31 // squareByValue multiplies number by itself, stores the 32 // result in number and returns the new value of number 33 int squareByValue( int number ) 34 { 35 return number *= number; // caller's argument not modified 36 37 } // end function squareByValue 38 39 // squareByReference multiplies numberRef by itself and 40 // stores the result in the variable to which numberRef 41 // refers in function main 42 void squareByReference( int &numberRef ) 43 { 44 numberRef *= numberRef; // caller's argument modified 45 46 } // end function squareByReference Changes number, but original parameter (x) is not modified. Changes numberRef, an alias for the original parameter. Thus, z is changed.
  • 6. x = 2 before squareByValue Value returned by squareByValue: 4 x = 2 after squareByValue   z = 4 before squareByReference z = 16 after squareByReference
  • 7. References and Reference Parameters References as aliases to other variables – Refer to same variable – Can be used within a function int count = 1; // declare integer variable count Int &cRef = count; // create cRef as an alias for count ++cRef; // increment count (using its alias)  References must be initialized when declared – Otherwise, compiler error – Dangling reference • Reference to undefined variable
  • 8. 1 // Fig. 3.21: fig03_21.cpp 2 // References must be initialized. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; 11 12 // y refers to (is an alias for) x 13 int &y = x; 14 15 cout << "x = " << x << endl << "y = " << y << endl; 16 y = 7; 17 cout << "x = " << x << endl << "y = " << y << endl; 18 19 return 0; // indicates successful termination 20 21 } // end main x = 3 y = 3 x = 7 y = 7 y declared as a reference to x.
  • 9. 1 // Fig. 3.22: fig03_22.cpp 2 // References must be initialized. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int x = 3; 11 int &y; // Error: y must be initialized 12 13 cout << "x = " << x << endl << "y = " << y << endl; 14 y = 7; 15 cout << "x = " << x << endl << "y = " << y << endl; 16 17 return 0; // indicates successful termination 18 19 } // end main 'y' : references must be initialized Uninitialized reference – compiler error.
  • 10. Default Arguments  Function call with omitted parameters – If not enough parameters, rightmost go to their defaults – Default values • Can be constants, global variables, or function calls  Set defaults in function prototype int myFunction( int x = 1, int y = 2, int z = 3 ); – myFunction(3) • x = 3, y and z get defaults (rightmost) – myFunction(3, 5) • x = 3, y = 5 and z gets default
  • 11. 1 // Fig. 3.23: fig03_23.cpp 2 // Using default arguments. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function prototype that specifies default arguments 9 int boxVolume( int length = 1, int width = 1, int height = 1 ); 10 11 int main() 12 { 13 // no arguments--use default values for all dimensions 14 cout << "The default box volume is: " << boxVolume(); 15 16 // specify length; default width and height 17 cout << "nnThe volume of a box with length 10,n" 18 << "width 1 and height 1 is: " << boxVolume( 10 ); 19 20 // specify length and width; default height 21 cout << "nnThe volume of a box with length 10,n" 22 << "width 5 and height 1 is: " << boxVolume( 10, 5 ); 23 Set defaults in function prototype. Function calls with some parameters missing – the rightmost parameters get their defaults.
  • 12. 24 // specify all arguments 25 cout << "nnThe volume of a box with length 10,n" 26 << "width 5 and height 2 is: " << boxVolume( 10, 5, 2 ) 27 << endl; 28 29 return 0; // indicates successful termination 30 31 } // end main 32 33 // function boxVolume calculates the volume of a box 34 int boxVolume( int length, int width, int height ) 35 { 36 return length * width * height; 37 38 } // end function boxVolume The default box volume is: 1   The volume of a box with length 10, width 1 and height 1 is: 10   The volume of a box with length 10, width 5 and height 1 is: 50   The volume of a box with length 10, width 5 and height 2 is: 100
  • 13. Unary Scope Resolution Operator  Unary scope resolution operator (::) – Access global variable if local variable has same name – Not needed if names are different – Use ::variable • y = ::x + 3; – Good to avoid using same names for locals and globals
  • 14. Function Overloading  Function overloading – Functions with same name and different parameters – Should perform similar tasks • I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  Overloaded functions distinguished by signature – Based on name and parameter types (order matters) – Name mangling • Encodes function identifier with parameters – Type-safe linkage • Ensures proper overloaded function called
  • 15. 1 // Fig. 3.25: fig03_25.cpp 2 // Using overloaded functions. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // function square for int values 9 int square( int x ) 10 { 11 cout << "Called square with int argument: " << x << endl; 12 return x * x; 13 14 } // end int version of function square 15 16 // function square for double values 17 double square( double y ) 18 { 19 cout << "Called square with double argument: " << y << endl; 20 return y * y; 21 22 } // end double version of function square 23 Overloaded functions have the same name, but the different parameters distinguish them.
  • 16. 24 int main() 25 { 26 int intResult = square( 7 ); // calls int version 27 double doubleResult = square( 7.5 ); // calls double version 28 29 cout << "nThe square of integer 7 is " << intResult 30 << "nThe square of double 7.5 is " << doubleResult 31 << endl; 32 33 return 0; // indicates successful termination 34 35 } // end main Called square with int argument: 7 Called square with double argument: 7.5   The square of integer 7 is 49 The square of double 7.5 is 56.25 The proper function is called based upon the argument (int or double).