3

For example, if I have:

if(x < 2*0.025) { ... }

Does the 2*0.025 get computed every time? Or does a 0.05 get substituted in so that the multiplication operation doesn't have to run every time?

In other words, is it more efficient to use 0.05 instead of 2*0.025?

Aman Aggarwal
  • 3,905
  • 4
  • 26
  • 38
Ryan
  • 5,883
  • 13
  • 56
  • 93

2 Answers2

5

Every compiler I know implements constant folding, i.e. calculates constant expressions at compile time, so there is no difference. The standard, however, does not mandate it:

A constant expression can be evaluated during translation rather than runtime, and accordingly may be used in any place that a constant may be.

You can explicitly disable this optimization with some compilers. For example, -frounding-math disables constant folding for floating point expressions in gcc.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Constant expressions are precomputed.

LaC
  • 12,624
  • 5
  • 39
  • 38