To return or not to return, this is a question for functions! Or, does it really matter?
Here is the story : I used to write code as follows:
Type3 myFunc(Type1 input1, Type2 input2){}
But recently, my project colleges told me that I should try as little as possible to avoid writing such a function, and suggest the next way by putting the return value in the input parameters.
void myFunc(Type1 input1, Type2 input2, Type3 &output){}
They convinced me that it’s better and faster due to the extra copy step when returning in the first method.
For me, I am beginning to believe that the second way is better in some situations, especially I have a few things that need to be returned or changed. For example: the second line of the next will be better and faster than the first, which avoids copying everything vecor<int>when you return.
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 can’t buy it. For example,
bool checkInArray(int value, vector<int> arr){}
will definitely be better than
void checkInArray(int value, vector<int> arr, bool &inOrNot){}
In this case, I think the first method directly returning the result is better in terms of better readability.
So, I'm confused (focused 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?
- Can we work better in both readability and code efficiency?
Edit:
, . , return-type functions, method chaining. , , , .
, , . , , C, C++ .. , ( ).