Ryan
Ryan

Reputation: 6057

Does the product of two constants get computed every time it is executed?

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?

Upvotes: 3

Views: 163

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726699

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.

Upvotes: 5

LaC
LaC

Reputation: 12824

Constant expressions are precomputed.

Upvotes: 0

Related Questions