Parameter Passing Mechanisms Reference Parameters.

Slides:



Advertisements
Similar presentations
AU/MITM/1.6 By Mohammed A. Saleh 1. Arguments passed by reference  Until now, in all the functions we have seen, the arguments passed to the functions.
Advertisements

Chapter 5 Functions.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
CPSC230 Computers & Programming I Lecture Notes 20 Function 5 Dr. Ming Zhang.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
C++ Functions CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Review of C++ Programming Part II Sheng-Fang Huang.
The switch Statement Selection Revisited. Problem Using OCD, design and implement a program that allows the user to perform an arbitrary temperature conversion.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
1 Chapter 9 Scope, Lifetime, and More on Functions.
1 C++ Loop Statements Repetition Revisited. 2 Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
CSC 221: Computer Programming I Fall 2001  top-down design  approach to problem solving, program design  focus on tasks, subtasks, …  reference parameters.
Controlling Function Behavior Sequence, Selection and Repetition.
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
Parameter Passing Mechanisms Reference Parameters Read § §
1 Simple Functions Writing Reuseable Formulas. In Math Suppose f (x) = 2 x 2 +5Suppose f (x) = 2 x 2 +5 f(5)=?f(5)=? f(5) = 2* =55f(5) = 2*
Functions Modules in C++ are called functions and classes Functions are block of code separated from main() which do a certain task every C++ program must.
CPSC 230 Computers and Programming I Spring 2003 Dr. Lynn Lambert.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Parameter Passing Mechanisms Reference Parameters § §
L function n predefined, programmer-defined l arguments, (formal) parameters l return value l function call, function invocation l function definition.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Reference parameters (6.2.3) We might need a function to return more than one value Find roots of a quadratic 2 return values. What are they? Get first.
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
Review 1 List Data Structure List operations List Implementation Array Linked List.
#include using namespace std; // Declare a function. void check(int, double, double); int main() { check(1, 2.3, 4.56); check(7, 8.9, 10.11); } void check(int.
C++ Loop Statements Repetition Revisited. Problem Using OCD, design and implement a function that, given a menu, its first valid choice, and its last.
Vectors One-Dimensional Containers. Problem A file contains a sequence of names and scores: Ann92 Bob84 Chris89... Using OCD, design and implement a program.
Exceptions in C++. Exceptions  Exceptions provide a way to handle the errors generated by our programs by transferring control to functions called handlers.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
Simple Functions Writing Reuseable Formulas. Problem Using OCD, design and implement a program that computes the area and circumference of an Australian.
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
CS201 – Introduction to Computing – Sabancı University 1 Built-in Arrays l C++ native array type (not the class version) l Two versions ä fixed size arrays.
1 What is a Named Constant? A named constant is a location in memory that we can refer to by an identifier, and in which a data value that cannot be changed.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
Reference Parameters There are two ways to pass arguments to functions: pass- by-value and pass-by-reference. pass-by-value –A copy of the arguments’svalue.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Prepared by Andrew Jung. Contents A Simple program – C++ C++ Standard Library & Header files Inline Functions References and Reference Parameters Empty.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
School of EECS, Peking University
Pointers and Pointer-Based Strings
Student Book An Introduction
Writing Reuseable Formulas
Operator Overloading.
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
6 Chapter Functions.
Introduction to C++ Introduced by Bjarne Stroustrup of AT&T’s Bell Laboratories in mid-1980’s Based on C C++ extended C to support object-oriented programming.
Engineering Problem Solving with C++ An Object Based Approach
Engineering Problem Solving with C++ An Object Based Approach
Pointers and Pointer-Based Strings
Predefined Functions Revisited
Presentation transcript:

Parameter Passing Mechanisms Reference Parameters

Problem Using OCD, design and implement a function that, given a string containing a long- distance telephone number, decomposes that number into its area code, exchange, and local number.

Preliminary Analysis Our function can receive the long-distance phone number through a string parameter. This problem requires that our function somehow communicate three values (area code, exchange, local number) to its caller. A function cannot return multiple values -- the return statement only returns one value: return Expression ;

Behavior Our program should receive from its caller a long-distance phone number (a string). It should check that the number is a valid long- distance number. If so, it should compute and pass back its area code, exchange, and local number.

Objects Description Type Movement Name area code string out areaCode exchange string out exchange local number string out localNum long distance string in ldNumber number

Operations Description Predefined? Library? Name receive a string yes built-in -- select part of yes string substr a string pass back 3 strings yes built-in ??

Algorithm 0. Receive ldNumber from caller, plus ‘empty’ variables areaCode, exchange and localNum. 1. Check that ldNumber is a long-distance number. 2. Fill areaCode with appropriate substring of ldNumber. 3. Fill exchange with appropriate substring of ldNumber. 4. Fill localNum with appropriate substring of ldNumber.

Discussion Since a function cannot return 3 strings, we will instead require the caller to pass us three string variables, which our function will then “fill in” with the appropriate values. Normal parameters are called value parameters and are built as copies of their arguments. Changing a value parameter changes the copy, not its corresponding argument.

Solution Reference parameters are parameters declared with an ampersand (&) following the parameter’s type (and before its name). A reference parameter is an alias (i.e., another name for) its corresponding argument. Changing the value of a reference parameter changes the value of its corresponding argument.

Coding #include // string class #include // isdigit() using namespace std; void ChopLDPhoneNumber(string ldNumber, // value: IN string & areaCode, // reference: OUT string & exchange, // reference: OUT string & localNum) // reference: OUT { for (int i = 0; i < ldNumber.size(); i++) // check all assert(isdigit(ldNumber[i])); // digits assert(ldNumber[0] == ‘1’ && // check for leading 1 ldNumber.size() == 11); // check number of digits areaCode = ldNumber.substr(1, 3); exchange = ldNumber.substr(4, 3); localNum = ldNumber.substr(7, 4); }

Testing The caller must now supply a variable for each reference parameter, to be “filled in” by the function. cout << “Enter a L-D phone number: “; string original, part1, part2, part3; cin >> original; ChopLDNumber(original, part1, part2, part3); cout << “\nArea code: “ << part1 << “\nExchange: “ << part2 << “\nLocal number: “ << part3 << endl;

Notes When function ChopLDNumber() is called: –a copy of argument original is made to create parameter ldNumber, –an alias of argument part1 is made to create parameter areaCode, –an alias of argument part2 is made to create parameter exchange, –an alias of argument part3 is made to create parameter localNum.

0. Before the function call Memory original part1 part2 part

1. ldNumber is created as a copy of original Memory original part1 part2 part ldNumber

2. areaCode is created as an alias for part1 Memory original part1 part2 part ldNumber areaCode

3. exchange is created as an alias for part2 Memory original part1 part2 part ldNumber areaCode exchange

3. localNum is created as an alias for part3 Memory original part1 part2 part ldNumber areaCode exchange localNum

4. The function checks ldNumber for validity Memory original part1 part2 part ldNumber areaCode exchange localNum

5. The function computes areaCode, changing part1 Memory original part1 part2 part ldNumber areaCode exchange localNum 616

6. The function computes exchange, changing part2 Memory original part1 part2 part ldNumber areaCode exchange localNum

7. The function computes localNum, changing part3 Memory original part1 part2 part ldNumber areaCode exchange localNum

8. The function returns, destroying all parameters Memory original part1 part2 part

9. part1, part2, and part3 now contain the information! Memory original part1 part2 part

Notes By default, parameters are value parameters. Reference parameters are specified by placing an ampersand after the parameter’s type. Reference parameters must be specified in both a function’s prototype and its definition, or a linking error will occur. Variables must be passed as arguments for reference parameters to fill, or a compiler error will occur.

Consider Copying argument original consumes time. Creating an alias for an argument takes almost no time. We could speed up calls to our function by making parameter ldNumber a reference parameter. However, we then run the risk of changing original if we mistakenly change ldNumber.

Solution Constant reference parameters are reference parameters whose declaration is preceded by the keyword. Constant reference parameters are reference parameters whose declaration is preceded by the keyword const. void ChopLDPhoneNumber(const string & ldNumber, // IN string & areaCode, // OUT string & exchange, // OUT string & localNum) // OUT //... Const reference parameters are read-only reference parameters -- aliases of their arguments -- but they cannot be changed.

0. Before the function call Memory original part1 part2 part

1. ldNumber is created as a const reference of original Memory original part1 part2 part ldNumber

Conclusion The rest of the function proceeds as before, except that all accesses to ldNumber now access original instead of the copy. Any attempt to change ldNumber will generate a compiler error (which makes sense, since its movement is IN, not OUT).

Discussion Copying time is not significant for simple types (e.g., int, char, double,...), but it is significant for class types (e.g., string, RandomInt,...). Use reference parameters for arguments whose movement is OUT. Use const reference parameters to store class arguments whose movement is IN. Use value parameters to store simple type arguments whose movement is IN.

Summary C++ provides 3 parameter mechanisms: –value, used for IN parameters whose arguments are simple types. –const reference, for IN parameters whose arguments are class types. –reference, for all OUT parameters.

Announcement Lab Test: Open books, Open notes.Lab Test: Open books, Open notes. –Wed. 2 hours. –3 programs. –You need prepare your money on your card. –You need to print all the results out in the lab. –You need in hand in the test sheet.