Return Value VS Parameter passing

Started by
3 comments, last by wah_on_2 21 years, 1 month ago
I heard many people said that they perfer using return value to return a changed value rather than using a reference parameter passing. Why? What is the reason? What is the different? Which one is better? Can explain for me? Thx a lot of ^^ e.g. //function 1 using reference parameter passing void func1(ref string Tmpstr) { Tmpstr = Tmpstr.Remove(0, 1); } //function 2 using return value string func2(string Tmpstr) { return Tmpstr.Remove(0, 1); } //main string str = "This is testing"; func1(ref str); //calling function 1 str = func1(str); //calling function 2
Advertisement
It depends on whether you want to change the original. Usually, you want to leave that decision up to the caller, so they can assign the return value themselves to overwrite the original.

EDIT: For example, using your example:

string str = "Testing";
string result;

result = str;
func1(result);

... vs ...

string str = "Testing";
string result;

result = func2(str);

Many prefer the second way.

[edited by - cgoat on March 18, 2003 3:20:50 PM]
Passing by reference and changing the parameter is faster in some cases. For example:

string jee = "jee";
jee = capitalize(jee);

Capitalize would create a copy of jee, capitalize it and return it by value (another copy). That''s two costly copies (unless I''m mistaken and RVO takes care of the return copy).

But this, directly manipulating version:

string jee = "jee";
capitalize(jee);

uses zero copies to do it''s job.
Passing by reference allows you to have an error return code if things fail in that function. Ex:

  //returns true if string can be capitalized, false otherwisebool  CapitalizeString (string& str);  


It also allows you to change more than one parameter at once:

  //returns true if all strings successfully capitalizedbool CapitalizeTwoStrings (string& str1, string& str2);  


These are admittedly stupid and trivial examples, but hopefully they demonstrate a couple reasons why to choose reference parameters in a method.
quote:Original post by Anonymous Poster
Passing by reference allows you to have an error return code if things fail in that function.
Although some people prefer throwing exceptions instead of using error return values. Maybe in the case of Capitalize() it could be reasonable to just return whether the string was modified or not (it was perhaps already capitalizad) and throwing an exception would be overkill since most people would want to silently ignore the return value.

This topic is closed to new replies.

Advertisement