Edit: This question is marked as duplicate and I can understand why but I searched and searched and I couldn't find the other question so hopefully this can be used as a funnel to the other question's answers. Also the other question doesn't have a best answer yet.
I don't have much experience with C++ but I always wondered about the following and couldn't find anything that explains which way is better anywhere:
1st Way: When writing functions, is it better to do this:
int value = Calculation(x, y);
int Calculation(int x, int y)
{
int value = x + y;
// Some More calculation involving value
return value;
}
2nd Way. or is it better to do it way:
int value = 0;
Calculation(value, x, y);
void Calculation(int& value, int x, int y)
{
value = x + y;
// Some More calculation involving value
}
From my experience in other Programming Languages, it is always good practice to write functions that take arguments and return the result but I always felt by doing so, I always have an extra variable declared within the function (the return variable) and every call to the function requires extra work from the Garbage Collector. I could be wrong but that's how I currently think about it.
The 2nd way, I only had to declare value once but I passed it by reference which means I'm giving extra work for the compiler every time I use the variable in function because it has to point to it every time.
So in Summary, my guess is that the 1st way is less work but an extra variable is added in memory. The 2nd way is less memory work but extra work needed to find the variable every time it's used in the function.
Finally my question, should I always stick to the 1st way?
Thanks so much!