logoalt Hacker News

tomsmeding02/20/20253 repliesview on HN

Modern C compilers are able to transform something like this:

for (int i = 0; i < n; i++) a += i;

To:

a += n * (n+1) / 2;

Is this an optimisation or a change in program semantics? I've never heard anyone call it anything slse than an optimisation.


Replies

dataflow02/20/2025

This will get a bit pedantic, but it's probably worthwhile... so here we go.

> Is this an optimisation or a change in program semantics?

Note that I specifically said something can be both an optimization and a change in semantics. It's not either-or.

However, it all depends on how the program semantics are defined. They are defined by the language specifications. Which means that in your example, it's by definition not a semantic change, because it occurs under the as-if rule, which says that optimizations are allowed as long as they don't affect program semantics. In fact, I'm not sure it's even possible to write a program that would be guaranteed to distinguish them based purely on the language standard. Whereas with tail recursion it's trivial to write a program that will crash without tail recursion but run arbitrarily long with it.

We do have at least one optimization that is permitted despite being prohibited by the as-if rule: return-value optimization (RVO). People certainly consider that a change in semantics, as well as an optimization.

show 1 reply
rat8702/20/2025

It can be, especially when you do something undefined the compiler can do all sorts of odd things while transforming code

pinoy42002/20/2025

Amazing it can do that. How does it work?

That definitely does seem to change its semantics to me. I am not a c expert but this surely has problems the previous one doesn’t?

show 1 reply