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 double
s.
I was warned that "Second code snippet could reside in a decimal precision issue".
There is no real difference between the 2 code snippets:
The precision aspect:
Both snippets deal only with double
s (with no conversion).
Storing the double
expression in a variable and then returning it is identical sematically to returning it directly.
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.