How much does the compiler reorder math operations?

89 points pixel293 42 comments

Sometimes when doing calculations I implement those calculations in a very specific order to avoid overflow/underflow. This is because I know what constraints those values have, and those constraints are defined elsewhere in the code. I've always assumed the compiler wouldn't reorder those operations and thus cause an overflow/underflow, although I've never actually researched what constraints are placed on the optimizer to reorder mathematical calculations.

For example a + b - c, I know the a + b might overflow so I would reorder it to (a - c) + b which would avoid the issue.

Now I'm using floats with values that I'm not worried about overflow/underflow. The calculations are numerous and annoying. I would be perfectly fine with the compiler reordering any or all of them for performance reasons. For readability I'm also doing sub-calculations that are stored in temporary variables, and again for speed I would be fine/happy with the compiler optimizing those temporaries away. Is there a way to tell the compiler, I'm not worried about overflow/underflow (in this section) and to optimize it fully?

Or is my assumption of the compiler honoring my order mistaken?