2

I am facing my colleague writing a function definition like this:

    typedef long double Real;
    void func(const Real& x, const Real &y);

I know it is somewhat bad to use pass-by-ref for primitive types, but what about long double? Its length is 80 bits, longer than a pointer of 64 bits on a regular machine nowadays. So maybe for long double, pass-by-ref is more efficient than pass-by-value?

Jimmy Chen
  • 305
  • 2
  • 11

1 Answers1

6

I'm hoping that your colleague has written it for another reason, that being that it stops any implicit conversions being made at the function calling site. It also prevents the parameter from being modified in the function body, which can help in the attainment of program stability, but that can be achieved by passing by const value.

Sometimes the overload resolution mechanism can be harmful, especially when introducing new overloads.

If it's there as a micro-optimisation strategy then that's a silly thing to do. If you can micro-optimise then so can the compiler. And writing typedef long double Real; is sillier still as (i) you've exchanged a standard term for a proprietary one and, (ii) Real implies there are no gaps in the representable numbers which we know is not the case. If a compiler with optimisations turned up to maximum produces code that runs faster if the long doubles are passed by reference, then consider switching your toolchain.

(I have worked with a 128 bit long double and always pass it by value.)

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • And that micro-optimisation strategy might be even worse, as with aliasing, any functions/methods (inside `func`) which might modify a outside `long double` would force to reload input parameters. – Jarod42 Nov 26 '21 at 12:33
  • Thank you for the thoughtful and comprehensive answer. I am wondering, as you mention compiler can do micro-optimization, does that mean compiler can auto-switch a call-by-value param to a call-by-ref. one? That seems a big behavioral change from the user's point of view. – Jimmy Chen Nov 29 '21 at 06:50
  • 1
    @JimmyChen See https://en.cppreference.com/w/cpp/language/as_if. The compiler can do anything it likes so long as it doesn't change the programmer's intention. – Bathsheba Nov 29 '21 at 06:58