Search code examples
c++runtime

Is there a difference between returning an intermediate variable and returning a function call directly?


Is there any difference between calling a function in return, and calling the function and then returning the value on runtime, like this:

my functions prototypes:

int aFunc(int...);
int bFunc(int...);

my first bFunc return line:

int bFunc(int...)
{
  ...
  return (aFunc(x,...));
}

my second bFunc return line:

int bFunc(int...)
{
  ...
  int retVal = aFunc(x,...);
  return retVal;
}

Solution

  • A good compiler should make both identical (at least when optimizations are enabled).

    Theoretically, there are two copy operations in bFunc:

    1. Into a local variable on the stack.

    2. From the local variable, into the "bottom" of the stack (bottom in the perspective of bFunc).

    If retVal is an object (class or structure) returned by-value and not by-reference (as in the case above), then the additional copy operation might yield an overhead proportional to the size of retVal.

    In addition to that, the fact that the copy constructor should be called twice (when dealing with an object), might prevent the compiler from applying the optimization in the first place.