0

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!

Maher Manoubi
  • 585
  • 1
  • 6
  • 18
  • 5
    There is no garbage collection in C++ – Rakete1111 Aug 17 '16 at 17:47
  • 1st way is better in term of readability: when reading a function call of the 2nd way, you don't know if an argument is passed as input or as output. The "return way" is less ambiguous – rocambille Aug 17 '16 at 17:51
  • ok good to know! I guess you have to be your own Garbage collection in c++ which I have to search how it's done. As I mentioned I'm still C++ beginner. – Maher Manoubi Aug 17 '16 at 17:52
  • 2
    @MaherManoubi C++ "garbage collection" is the use of [automatic objects](https://en.wikipedia.org/wiki/Automatic_variable) – NathanOliver Aug 17 '16 at 17:55

0 Answers0