Reputation: 35
I have a method that is returning a CString and placing it into a variable, however this variable is a parameter in the method. Is there a better way to assign the return of the method into the variable?
Example:
CString foo = "foo";
foo = MakeBar(foo);
Upvotes: 1
Views: 116
Reputation: 179930
The question is how your MakeBar()
function is typically used, how it is implemented. If there's a sizeable fraction of foo2 = MakeBar(foo1)
calls, then it's better to have a return value. If you're sure that the output of MakeBar()
always replaces the input, then the void MakeBar(CString &foo)
form is better.
Upvotes: 0
Reputation: 35188
Your code is fine. It's common (and often good practice) to write functions that don't modify their arguments. In your case, you want to overwrite foo
, so you have to assign the result to itself.
This idiom is very common in other languages that have immutable strings.
Upvotes: 4
Reputation: 347396
Pass foo by reference into the function. In that way it's understood that it will be an input/output parameter.
void MakeBar(CString &foo)
{
if(foo == "foo")
foo = "bar";
}
//...
CString foo = "foo";
MakeBar(foo);
Upvotes: 3