Return vs. Not Return of functions?

Viewed 2874

Return or not return, it's a question for functions! Or, does it really matter?


Here goes the story: I used to write code like the following:

Type3 myFunc(Type1 input1, Type2 input2){}

But recently my project colleges told me that I should try, as mush as possible, to avoid writing function like this, and suggest the following way by putting the returned value in the input parameters.

void myFunc(Type1 input1, Type2 input2, Type3 &output){}

They convinced me that this is better and faster because of the extra copying step when returning in the first method.


For me, I start to believe that the second method is better in some situations, especially I have multiple things to return or modify. For example: the second line of following will be better and faster than the first one as avoiding copying the whole vecor<int> when returning.

vector<int> addTwoVectors(vector<int> a, vector<int> b){}
void addTwoVectors(vector<int> a, vector<int> b, vector<int> &result){}:

But, in some other situations, I cannot buy it. For example,

bool checkInArray(int value, vector<int> arr){}

will be definitely better than

void checkInArray(int value, vector<int> arr, bool &inOrNot){}

In this case, I think the first method by directly return the result is better in terms of better readability.


In summary, I am confused about (emphasis on C++):

  • What should be returned by functions and what should not (or try to avoid)?
  • Is there any standard way or good suggestions for me to follow?
  • Can we do better in both in readability and in code efficiency?

Edit: I am aware of that, under some conditions, we have to use one of them. For example, I have to use return-type functions if I need to achieve method chaining. So please focus on the situations where both methods can be applied to achieve the goal.

I know this question may not have a single answer or sure-thing. Also it seems this decision need to be made in many coding languages, like C, C++, etc. Thus any opinion or suggestion is much appreciated (better with examples).

7 Answers
Related