0

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.

Alex Riveron
  • 389
  • 1
  • 10
  • 1
    Constant folding is a compiler optimization, that happens like all others under the "as-if" rule. If well-defined code changes behaviour after optimisation, then the compiler has a bug. – Quentin Apr 22 '21 at 18:41
  • Thank you @Quentin this is actually helpful. I was not aware of the "as-if" rule, looking into it now. – Alex Riveron Apr 22 '21 at 18:44
  • `What is the expected behavior of C++ constant folding of integer expressions?` The exact same as the behavior without any constant folding. – KamilCuk Apr 22 '21 at 18:46
  • 1
    So it appears, that potentially the only time the "as-if" rule would not apply would be for copy/move elision, where there are side effects in the copy or move constructors, otherwise, I should be good. – Alex Riveron Apr 22 '21 at 18:52

1 Answers1

3

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.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Just adding a note here in case any one else runs into this Q&A in the future. There are some exceptions to the "as-if" rule. I found this [post](https://stackoverflow.com/questions/15718262/what-exactly-is-the-as-if-rule) useful. – Alex Riveron Apr 22 '21 at 19:06