pass-by-reference

12
Pass-By-Reference 03/16/11

Upload: jock

Post on 06-Jan-2016

28 views

Category:

Documents


0 download

DESCRIPTION

03/16/11. Pass-By-Reference. Getting Info Back from a Function. return can only return one value back to a calling function. Sometimes you want to pass more than one value. Example. Want to scale a rectangle in graphic. One foot is scaled to 1/4 inch. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pass-By-Reference

Pass-By-Reference

03/16/11

Page 2: Pass-By-Reference

Getting Info Back from a Function

return can only return one value back to a calling function.

Sometimes you want to pass more than one value.

Page 3: Pass-By-Reference

Example

Want to scale a rectangle in graphic. One foot is scaled to 1/4 inch. I want a new measure for both length and

width.– Must transmit more than one value by to

calling program. scale.cpp

Page 4: Pass-By-Reference

Pass-By-ReferenceSyntaxvoid scale(double& ln, double& wd);

& indicates pass-by-reference parameter

Page 5: Pass-By-Reference

Pass-By-Reference

Call:scale(length, width);

Function Heading: void scale(double& ln, double& wd)

ln and wd contain address of length and width Changes in the parameters affect arguments, length

and width.

Page 6: Pass-By-Reference

Stock Function

Write a function that takes the value of a

stock today and its value a year ago. It

should give the difference in price and the

percent change.

e.g. Apple $305.97 Thursday, $225.50 one

year ago.

Page 7: Pass-By-Reference

Movie Time Function

Write a Function, movieTime( ), that has an integer parameter named minutes and two integer parameters named hours and min. The function is to convert the passed number of minutes a movie lasts into an equivalent number of hours and minutes. Using pass by reference the function should directly alter the respective arguments of the calling function.

Page 8: Pass-By-Reference

Which to Use

Pass-by-reference Pass-by-reference Want a change in the associated argument Want a change in the associated argument

Pass-by-valuePass-by-value No change wanted in argumentNo change wanted in argument

fig5_13.cppfig5_13.cpp has both has both

Page 9: Pass-By-Reference

Functions to Improve Programs

Break up into partsEasier to readDebug and Test one piece at a timeRPS.cpp

Page 10: Pass-By-Reference

Use Right Kind of Function

One value to return Function that returns a single value e.g. double area(double l, double w);

No value to return void function e.g. void instructions();

Page 11: Pass-By-Reference

Use Right Kind of Function

More one value to return void function Reference parameters e.g. void scale(double &l, double &w);

Page 12: Pass-By-Reference

To Do

p. 179 #1 & 3Read pp. 180-188

Skipping Recursion at the end of Ch. 5 A function calling itself. Generally avoid that. Can make some problems simpler