Home > Blockchain >  Is the a difference between returning a value and saving it to a variable and returning that variabl
Is the a difference between returning a value and saving it to a variable and returning that variabl

Time:02-01

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".

CodePudding user response:

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.

CodePudding user response:

From a pure semantic point of view, the two codes have absolutely the same effect. The modulus is computed as a double-precision number. Whether it is temporarily stored in a double variable or not makes no difference. By the way, the optimizing compiler will most probably implement the first version like the second, recognizing that the temporary storage is useless.

Anyway, from a pragmatic point of view a difference could exist on the x86/x64 platform where the FPU registers are 80 bits rather than 64. In some optimization modes, the data is kept in those registers rather than copied back to memory with rounding. So the 80 bits computed value could be used straight from the FPU register for the next computations.

Anyway, it is unlikely that in this circumstance, using a temporary will force rounding to 64 bits. In any case, the second form could only be more accurate.

  • Related