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.

Slides:



Advertisements
Similar presentations
CSE202: Lecture 12The Ohio State University1 Function Calling.
Advertisements

Computer Programming w/ Eng. Applications
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
CS201 – Introduction to Computing – Sabancı University 1 First Midterm Exam l November 22, 2008, Saturday, 10:40 – 12:20, max 100 minutes l One A4 size.
Parameter Passing Mechanisms Reference Parameters.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 5. Functions.
1 Lecture 18:User-Definded function II(cont.) Introduction to Computer Science Spring 2006.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
Computer Science 1620 Reference Parameters. Parameters – Pass by Value recall that the parameter of a function is assigned the value of its corresponding.
Programming Pointers. Variables in Memory x i c The compiler determines where variables are placed in memory This placement cannot.
Imperative Programming. Heart of program is assignment statements Aware that memory contains instructions and data values Commands: variable declarations,
Chapter 7 Functions.
Classes: From Use to Implementation
Functions Parameters & Variable Scope Chapter 6. 2 Overview  Using Function Arguments and Parameters  Differences between Value Parameters and Reference.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Parameter Passing Mechanisms Reference Parameters Read § §
1 Advanced Issues on Classes Part 3 Reference variables (Tapestry pp.581, Horton 176 – 178) Const-reference variables (Horton 176 – 178) object sharing:
CPS120: Introduction to Computer Science Functions.
Software Design 8.1 A Rose by any other name…C or Java? l Why do we use Java in our courses (royal we?)  Object oriented  Large collection of libraries.
Parameter Passing Mechanisms Reference Parameters § §
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
Functions Overview Functions are sequence of statements with its own local variables supports modularity, reduces code duplication Data transfer between.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
L what are executable/non-executable statements l out of the ones below which constructs are executable #include p=3.14; const double PI=3.14; int myfunc(int);
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.
A Computer Science Tapestry 6.1 Classes: From Use to Implementation l We’ve used several classes, a class is a collection of objects sharing similar characteristics.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
CMSC 202 Lesson 6 Functions II. Warmup Correctly implement a swap function such that the following code will work: int a = 7; int b = 8; Swap(a, b); cout.
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.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
Chapter 16 Pointers and Arrays Pointers and Arrays We've seen examples of both of these in our LC-3 programs; now we'll see them in C. Pointer Address.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
LECTURE 3 PASS BY REFERENCE. METHODS OF PASSING There are 3 primary methods of passing arguments to functions:  pass by value,  pass by reference, 
Parallel Arrays? ANSI-C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Pointers and Pointer-Based Strings
New Structure Recall “average.cpp” program
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Lecture 6 C++ Programming
Reference parameters (6.2.3)
Multiple Files Revisited
Object Oriented Programming COP3330 / CGS5409
Pass by Reference, const, readonly, struct
Pointers, Dynamic Data, and Reference Types
6 Chapter Functions.
Simulating Reference Parameters in C
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
C++ Pointers and Strings
Pointers and References
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
CS150 Introduction to Computer Science 1
Based on slides created by Bjarne Stroustrup & Tony Gaddis
CS150 Introduction to Computer Science 1
Multiple Files Revisited
CS150 Introduction to Computer Science 1
CMSC 202 Lesson 6 Functions II.
C++ Pointers and Strings
Presentation transcript:

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 and last name of a user and return them 2 return values Functions are limited to one return value using return When you need to return several values back from a function Use reference parameters The idea is that when the value of the parameter is modified, function modifies the value of the corresponding argument as well

Value Parameters - Pass by value The parameters we have seen so far are value parameters their arguments are passed by value if you change the value of a parameter in function, corresponding argument does NOT change in the caller function Example: see passbyvalue.cpp (not in book) parameter a changes in function average, but corresponding argument, num1, does not change in main Enter two integers: in main before calling average: num1 = 10, num2 = 15 beginning of function average: a = 10, b = 15 end of function average: a = 25, b = 15 average is 12.5 in main after calling average: num1 = 10, num2 = 15

Reference Parameters – Pass by Reference Reference parameters are used to change the value of the argument in the caller function as well ampersand (&) between type and name void myfunction (int & num) if you change the value of a reference parameter in function, corresponding argument changes in the caller function Argument of a reference parameter must be a variable This is a reasonable rule, because otherwise its value won’t change See passbyreference.cpp (not in book) parameter a changes in function average; corresponding argument, num1, changes in main as well Enter two integers: in main before calling average: num1 = 10, num2 = 15 beginning of function average: a = 10, b = 15 end of function average: a = 25, b = 15 average is 12.5 in main after calling average: num1 = 25, num2 = 15

Underlying Mechanisms For value parameters, the arguments’ values are copied into parameters arguments and parameters have different memory locations double average (int a, int b) average(num1, num2) copy value main function

Underlying Mechanisms For reference parameters, the parameter and the argument share the same memory location parameter is an alias of argument double average (int & a, int b) average(num1, num2) refers to the same memory location copy value main function

Example: Swap Write a function that swaps the values of its two integer parameters void swap(int & a, int & b) { int temp; temp = a; a = b; b = temp; } How do we use this in main? int a=5, b=8; swap(a,b); // a becomes 8, b becomes 5 swap(a,5); // syntax error, arguments must be variables

Examples What’s prototype for a void function that takes a string as parameter and returns the number of vowels and consonants in it? void letters(string s, int & vowels, int & consonants); What’s prototype for a void function that returns the number of hours, minutes in N seconds. Where N is a parameter? void TimeConversion(int N, int & hours, int & minutes);

Reference Parameters are not only to return multiple values Even if you have a single value to return, you may prefer to return it as a reference parameter, not as the return value of the function. ToLower function, defined in strutils, changes its argument to all lowercase. It is actually a void function, i.e. does not return anything as the function’s return value Prototype is void ToLower(string & s); Example use string s = "HeLLo"; ToLower(s); // s becomes “hello”

Example (See roots.cpp) Roots of a quadratic equation ax 2 + bx + c = 0 what could be a prototype? void roots(double a, double b, double c, double & r1, double & r2); What happens if one root? no roots? how will you inform the caller function about the number of roots? necessary in order to let the caller function to interpret arguments for r1 and r2 Solution: let the function return (as the return value) an integer value for the number of roots So, the prototype becomes int roots(double a, double b, double c, double & r1, double & r2);

Parameter Passing: const-reference Pass by value (value parameters) has overheads copying the value memory allocation for both parameter and argument Sometimes we want to avoid the overhead of making the copy, but we don’t want to allow the argument to be changed. const-reference parameters avoid copies, but cannot be changed in the function trying to change a const-reference parameter is a syntax error defined with const before a reference parameter void demo (const int & num, const string & s);

Example Count number of occurrences of a letter in a string Write a function for it Look at every character in the string int LetterCount(const string& s, const string& letter) // post: return number of occurrences of letter in s { int k, count = 0, len = s.length(); for(k=0; k < len; k++) { if (s.substr(k,1) == letter) { count++; } return count; } Calls below are legal int ec = LetterCount("elephant", "e"); string s = "hello"; cout << LetterCount(s, "a");

General rules for Parameters Const-reference parameters allow constants and literals to be passed For example, “elephant” cannot be passed as an argument for a reference parameter, but it is ok with const-reference Some good-programming tips Built-in types (int, double, bool, char) - pass by value unless you change it and return from the function All other types - pass by const-reference unless you change it and return from the function When you change and want to return the changed value, use reference parameters What about using classes as the parameter type? use reference parameters if you are changing the state of the parameter object that is why we used reference parameters for Robot objects use const reference if you are not changing the state of the parameter object