tags:

views:

68

answers:

3

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);
+3  A: 

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);
Brian R. Bondy
+4  A: 

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.

Kristo
it is good functional style, much better than having side effects imho
jk
A: 

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.

MSalters