Search code examples
c++variablesreturn-value

Is the a difference between returning a value and saving it to a variable and returning that variable?


I was working on college stuff and I wondered of the difference between this:

double TComplejo::Mod(void) const
{
    double a = sqrt(re * re + im * im);
    return a;
}

and this:

double TComplejo::Mod(void) const
{
    return sqrt(re * re + im * im);
}

Both re and im are doubles.

I was warned that "Second code snippet could reside in a decimal precision issue".


Solution

  • There is no real difference between the 2 code snippets:

    1. The precision aspect:
      Both snippets deal only with doubles (with no conversion).
      Storing the double expression in a variable and then returning it is identical sematically to returning it directly.

    2. The performance aspect:
      Due copy-elision (RVO) the generated asembly code is likely to be the same with modern compilers. Even before C++17 with mandatory copy elision, most compilers would produce the same code for the 2 snippets.

    For example: as you can see here (Godbolt) GCC (with -O2) produces the same code for both snippets.

    This post discussing What exactly is the "as-if" rule? contains some more relevant info that should make it clear why the 2 snippets should behave the same.