What is the expected behavior of C++ constant folding of integer expressions?

185 views Asked by At

For example, let's say we have a function that replaces the two least significant decimal places of an int with 0:

int Remove2LSD(int x)
{
  return x / 100 * 100;
}

If we pass 2052 we should expect a return of 2000, 2199 should return 2100.

It does not appear that constant folding occurs with the MSVC compiler if you run it with or without optimizations, which is what I would expect, since x / 100 should be evaluated before * 100, and we're not evaluating x / 100 at compile time. The argument x comes from runtime input.

I don't think that I have to worry about constant folding changing return x / 100 * 100; to return x; , based on my assumptions and testing; however, I was hoping to find better documentation regarding the expected behavior in this case, rather than just relying on my assumptions and tests.

Is there any good documentation about this behavior? I've looked on SO and other places on the web and have not been able to find documentation that was useful to me.

1

There are 1 answers

1
HolyBlackCat On BEST ANSWER

Most optimizations (including constant folding) are governed by the as-if rule. It states that any optimization is allowed if and only if it doesn't change the observable behavior of the program (it works "as if" it was unoptimized).

So no, you don't need to worry about constant folding here.