Parameter Passing Mechanisms Reference Parameters §10.1 - §10.3 1.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Subprogram Control - Data sharing Mechanisms to exchange data Arguments - data objects sent to a subprogram to be processed. Obtained through  parameters.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Parameter Passing Mechanisms Reference Parameters.
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Chapter 5 Functions.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Computer programming1 Arrays. Computer programming2 ARRAYS Motivation Introduction to Arrays Static arrays Arrays and Functions Arrays, Classes, and typedef.
Pointers A pointer is a variable that contains memory address as its value. A variable directly contains a specific value. A pointer contains an address.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 9 Pointers and Dynamic Arrays.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Basic Elements of C++ Chapter 2.
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.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it.
Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Cpt S 122 – Data Structures Classes: A Deeper Look Part.
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 8: User-Defined Simple Data Types, Namespaces, and the string Type.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Introducing C++ Programming Lecture 3 Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
POINTERS.
Review 1 List Data Structure List operations List Implementation Array Linked List.
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.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 6 Functions.
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.
Lecture 5 functions 1 © by Pearson Education, Inc. All Rights Reserved.
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
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.
Pointers. The memory of your computer can be imagined as a succession of memory cells, each one of the minimal size that computers manage (one byte).
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
C++ Functions A bit of review (things we’ve covered so far)
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Procedural and Object-Oriented Programming
Chapter Topics The Basics of a C++ Program Data Types
School of EECS, Peking University
Pointers and Pointer-Based Strings
Student Book An Introduction
Writing Reuseable Formulas
Pointers and References
Pointers and Pointer-Based Strings
Java Programming Language
Predefined Functions Revisited
Structure (i.e. struct) An structure creates a user defined data type
Pointers and References
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
Presentation transcript:

Parameter Passing Mechanisms Reference Parameters § §10.3 1

Problem Using OCD, design and implement a function that, given a string containing an IP address, decomposes it into its four network/host information blocks (aaa, bbb, ccc, ddd) and returns these values. 2 IPv4 (Internet Protocol) addresses are expressed using "dotted decimal" notation: aaa.bbb.ccc.ddd where aaa, bbb, ccc, and ddd are 1-byte (8-bit) integers that provide network or host information. ipv6 16 bytes Find/locate IP address

Preliminary Analysis Our function can receive the IP address through a string parameter. This problem requires that our function somehow communicate four values (the network/host information blocks ) back to its caller. A function cannot return multiple values — the return statement only returns one value: return expression; 3

Behavior Our subprogram should receive from its caller an IP address (a string). It should compute and pass back its four network/host information blocks or halt execution if it did not receive a valid IP address. 4

Objects Description Type Name IP address stringipAddr first block string info1 second block string info2 third block string info3 fourth block string info4 5 Movement to back Where? main() or in function

Operations Description Predefined? Library? Name 6 receive a stringyesbuilt-innone select part of a yes string substr() string search a stringyes string find() halt if erroryes cassert assert() pass back 4 strings yes built-in ??

Algorithm 0. Receive ipAddress from caller and declare four variables info1, info2, info3, and info4. 1. Fill info1 with appropriate substring of ipAddr or halt if it can't be found. 2. Fill info2 with appropriate substring of ipAddr or halt if it can't be found. 3. Fill info3 with appropriate substring of ipAddr or halt if it can't be found. 4. Fill info4 with appropriate substring of ipAddr or halt if it can't be found. 7

Discussion Since a function cannot return 4 strings, we will instead require the caller to pass it four string variables as arguments, which our function will then assign values. Parameters used up to now are called value parameters; they are built as copies of their arguments. Changing a value parameter changes the copy, not its corresponding argument. So, we need a different kind of parameter. 8

Solution: Reference Parameters A reference parameter is an alias (i.e., another name) for its corresponding argument. They share memory locations. Changing the value of a reference parameter changes the value of its corresponding argument. In C++, reference parameters are declared with an ampersand (&) following the parameter’s type (and before its name). 9 & is also the "address of" operator

Coding void chopIPAddress(string ipAddr, // value: TO string & info1, // reference: BACK string & info2, // reference: BACK string & info3, // reference: BACK string & info4) // reference: BACK { int dot1 = ipAddr.find(".", 0); assert(dot1 != string::npos); info1 = ipAddr.substr(0, dot1); int dot2 = ipAddr.find(".", dot1 + 1); assert(dot2 != string::npos); info2 = ipAddr.substr(dot1 + 1, dot2 - dot1 - 1); int dot3 = ipAddr.find(".", dot2 + 1); assert(dot3 != string::npos); info3 = ipAddr.substr(dot2 + 1, dot3 - dot2 - 1); assert(ipAddr.find(".", dot3 + 1) == string::npos); info4 = ipAddr.substr(dot3 + 1, ipAddr.size() - dot3 - 1); } 10

Testing The caller must now supply a variable for each reference parameter, to be "filled in" by the function. 11 cout << "Network/Host blocks are:\n" << part1 << endl << part2 << endl << part3 << endl << part4 << endl; cout > ipAddress; chopIPAddress(ipAddress, part1, part2, part3, part4);

Notes When function chopIDAddress() is called: – –ipAddr is allocated a memory location and a copy of the argument ipAddress is stored there – –Each of the parameters info1, info2, info3, info4 is an alias of the corresponding argument — part1, part2, part3, part4; they share the same memory location; that is, info1 and part1 are names of the same memory location, as are info2 and part2, info3 and part3, info4 and part4. 12

0. Before the function call Memory ipAddress part1 part2 part part4 cout > ipAddress; 13 ????????

1. ipAddr is created as a copy of ipAddress Memory ipAddress part1 part2 part3 ipAddr part4 chopIPAddress(ipAddress, part1, part2 part3, part4); ????????

2. info1,..., info4 are created as aliases for part1,..., part4 Memory part1 part2 part3 15 ipAddress part4 info1 info2 info3 info4 ipAddr chopIPAddress(ipAddress, part1, part2 part3, part4); ????????

3. The function computes info1, changing part1 16 Memory part1 part2 part3 ipAddress part4 info1 info3 info4 ipAddr 153 int dot1 = ipAddr.find(".", 0); assert(dot1 != string::npos); info1 = ipAddr.substr(0, dot1); info2 ??????

4. The function computes info2, changing part2 17 Memory part1 part2 part3 ipAddress part4 info1 info2 info3 info4 ipAddr int dot2 = ipAddr.find(".", dot1 + 1); assert(dot2 != string::npos); info2 = ipAddr.substr(dot1 + 1, dot2 - dot1 - 1); ????

5. The function computes info3, changing part3 18 Memory part1 part2 part3 ipAddress part4 info1 info2 info3 info4 ipAddr int dot3 = ipAddr.find(".", dot2 + 1); assert(dot3 != string::npos); info3 = ipAddr.substr(dot2 + 1, dot3 - dot2 - 1); ?

6. The function computes info4, changing part4 19 Memory part1 part2 part3 ipAddress part4 info1 info2 info3 info4 ipAddr assert(ipAddr.find(".", dot3 + 1) == string::npos); info4 = ipAddr.substr(dot3 + 1, ipAddr.size() - dot3 - 1);

7. The function returns, destroying all parameters Memory 20 part1 part2 part3 ipAddress part } info1 info2 info3 info4 ipAddr

8. part1,..., part4 now contain the information! 21 Memory part1 part2 part3 ipAddress part cout << "Network/Host blocks are:\n" << part1 << endl << part2 << endl << part3 << endl << part4 << endl

Notes By default, parameters are value parameters. Reference parameters are specified by placing an ampersand after the parameters 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. 22

An Alternative to Value Parameters Copying argument ipAddress consumes time. Creating an alias for an argument takes almost no time. We could speed up calls to our function by making parameter ipAddr a reference parameter. However, we then run the risk of changing ipAddress if we mistakenly change ipAddr. 23

Constant reference parameters are reference parameters whose declaration is preceded by the keyword const. void chopIPAddress(const string & ipAddr, // TO string & info1, // BACK string & info2, // BACK string & info3, // BACK string & info4) // BACK //... Const reference parameters are read-only reference parameters -- aliases of their arguments -- but they cannot be changed. 24

0. Before the function call 25 Memory ipAddress part1 part2 part part4 ????????

1. ipAddr is created as a const reference of original ipAddr 26 read-only Memory ipAddress part1 part2 part part4

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

Discussion 28 Copying time is not significant for simple types (e.g., int, char, double,...), but it is significant for class types (e.g., string, RandomInt,...). So use value parameters to store simple type arguments whose movement is TO. Use reference parameters for arguments whose movement is BACK or TO & BACK Use const reference parameters to store class arguments whose movement is TO.