2016-07-10 - constexpr and floating-point

in C++ a constexpr keyword can be applied to a function. such a function can either be evaluated at run-time or (if possible) at compile-time. now let's have a look at the following trivial example:

#include <iostream>
using namespace std;
 
constexpr double foo(double a, double b)
{
  return a + b;
}
 
int main()
{
  double a,b;
  cin >> a;
  cin >> b;
 
  // 1) compile-time:
  cout << foo(1.333, 2.666) << endl;
  // 2) run-time:
  cout << foo(a, b) << endl;
}

assuming used will provide a = 1.333 and b = 2.666, it is pretty obvious, that both cases should print the same result. now an interesting question part – what will happen in case of cross-compilation, where target architecture has a different floating-point precision, than the host, performing a cross-compilation? this question arose during a post-seminar discussion, on one of the conferences. since i do a lot of embedded programing it turned out to be quite an interesting.

at first one could think results may differ, since it would be natural for an implementation to use double type and operations, offered by a local hardware.

fortunately C++14 makes, section 7.1.5/7 makes it clear:

A call to a constexpr function produces the same result as a call to an equivalent non-constexpr function in all respects except that a call to a constexpr function can appear in a constant expression.

so developers are on a safe side – results will always be the same. however compilers' developers have one more extra thing to do, when implementing cross-compilation, in a context of constexpr functions – they need to emulate floating-point of a target hardware, if it differs from host's.

blog/2016/07/10/constexpr_and_floating-point.txt · Last modified: 2016/07/10 11:32 by basz
Back to top
Valid CSS Driven by DokuWiki Recent changes RSS feed Valid XHTML 1.0