3

Herein, similar questions were asked for C#:

Are arithmetic operations on literals in C# evaluated at compile time?,

and java:

Are arithmetic operations on literals calculated at compile time or run time?.

Considering C++, will the following calculations be evaluated during run- or compile-time? The first is to define a built-in type, the second is to be a function argument.

Yet please consider them for all 4 basic arithmetic operations as well as with other built-in types, e.g. an int instead of the double below.

  • double testDouble = 2.0 + 2.0;
  • aUserDefinedType testUserDefinedTypeObject ( aMemberVariable*std::pow(someOtherVariable, 1.0/8.0) );
Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Herpes Free Engineer
  • 2,425
  • 2
  • 27
  • 34
  • 1
    [Go ahead and find out](https://godbolt.org/). It's not required, an optimizing compiler might/will do it. – Hatted Rooster Feb 18 '18 at 13:01
  • 1
    Constant arithmetic expressions such as `2.0 + 2.0` might or might not be evaluated during compile time. – Ron Feb 18 '18 at 13:05

1 Answers1

9

It depends on your compiler and its optimization level when building the code.

There is no intrinsic guarantee of compile time evaluation, but most compilers will evaluate constant expressions at compile time when optimizations are turned on.

There is also constexpr which can also help the compiler know what can be evaluated at compile time.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • Accordingly, I presume that it is always recommended to evaluate such expressions beforehand, and not to leave this to the compiler's preference? e.g. instead of `1.0/8.0`, writing `0.125` is always preferable? Please consider this in the context of very high number of FLOPT computations. – Herpes Free Engineer Feb 18 '18 at 13:09
  • 2
    @Kuti any modern optimizing compiler *will* evaluate trivial expressions like that at compile time as soon as optimizations are turned on. You should write the code in the way that makes it the most clear and trust the optimizer (it's smarter than you) - readability counts for *a lot* and micro-optimization like that that the compiler does *anyway* will just hurt readability. – Jesper Juhl Feb 18 '18 at 13:14
  • 2
    The conformance parameters of the compiler matter. An exact operation like 1./8. is always fine, but for instance 1./3. depends on the rounding mode and thus cannot be evaluated at compile-time when compilers support rounding modes (-frounding-math for gcc). – Marc Glisse Feb 18 '18 at 13:29