Floating-point arithmetic at compile time

Are floating point calculations that use compile-time integers performed at compile time or at run time? For example, when the division operation is calculated in:

template <int A, int B> inline float fraction() { return static_cast<float>(A) / B; } 
+2
c ++ math floating-point compile-time
source share
5 answers

I believe this implementation is defined, but most compilers will evaluate constant expressions at compile time. However, even if your version does not have the following modification:

 template <int A, int B> inline float fraction() { static const float f = static_cast<float>(A) / B; return f ; } 

at least ensures that an expression is evaluated only once if it is evaluated at run time.

+1
source share

For something so simple, the compiler will probably do this at compile time. In fact, the compiler is likely to do this at compile time even without templates, if all values ​​are known at compile time: i.e. If we have an inline float fraction(int A, int B) , this will probably do compile time division if we call fraction(1,2) .

If you want the force compiler to compile at compile time, you will need to use some template metaprograms, and I'm not sure if you can make it work with floating point, point arithmetic. But here is a basic example of a method:

 // Something similarly simple that doesn't use floating-point ;) template <int A, int B> struct Product { enum { value = A * B }; }; // Later: ... Product<3, 4>::value ... 
+2
source share

It is best to look at the generated code - there is no guarantee that floating point operations will be performed during compilation, but at higher levels of optimization they can potentially be, in particular, for something simple.

(Some compilers can avoid this because, for some architectures, floating point behavior is configured at runtime. The results for an operation performed at compile time can potentially differ from the results of the same operation performed at runtime.)

+1
source share

You should wait for gcc 4.6 with the implementation of the C ++ 0x constexpr keyword .

+1
source share

Neither the C nor C ++ standards require constant expressions of any strip to be computed at compile time, but they allow this. Most compilers released in the last 20 years will evaluate arithmetic expressions, therefore, if you do not perform a function call or embed code, it is important that it be as simple as the user.

If the volume of these expressions is limited to one file, you can always use the preprocessor and #define FRACTION(a,b) (float(a)/float(b)) for convenience. I do not recommend doing this in the header unless you have a good scheme to prevent infection with any #include file.

+1
source share

All Articles