120 likes | 242 Views
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.
E N D
03/16/11 Pass-By-Reference
Getting Info Back from a Function • returncan 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. • I want a new measure for both length and width. • Must transmit more than one value by to calling program. • scale.cpp
Pass-By-Reference • Syntax void scale(double& ln, double& wd); • & indicates pass-by-reference parameter
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.
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.
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.
Which to Use • Pass-by-reference • Want a change in the associated argument • Pass-by-value • No change wanted in argument • fig5_13.cpp has both
Functions to Improve Programs • Break up into parts • Easier to read • Debug and Test one piece at a time • RPS.cpp
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();
Use Right Kind of Function • More one value to return • void function • Reference parameters • e.g. void scale(double &l, double &w);
To Do • p. 179 #1 & 3 • Read pp. 180-188 • Skipping Recursion at the end of Ch. 5 • A function calling itself. • Generally avoid that. • Can make some problems simpler