I think it was pretty clear I wanted an answer to a question, not to solve some concrete problem... and it's a question with potential for some "debate", which I think is interesting, but not everyone has to agree
What might not have been clear enough was the scope (specifically the GNU-style attribute), which I tried to fix after getting pretty diverse answers. Yes, that's probably my fault. It turns out that, although a "pure function" is well-defined in a mathematical way, you can come to very different interpretations looking at (technical) code, depending on the abstraction level you use.
I also
think that the example I found one day later that could lead to an incorrect program when the guarantees expected by the "pure" attribute are applied answers the initial question, but maybe someone still wants to comment on that...
Just regarding "premature optimization": Yes, changing the function in a way the "pure" attribute can be safely applied in order to enable compiler optimizations would be an example, but applying attributes in general isn't. Attributes help in several ways:
- The programmer using an API to better understand its semantics
- The compiler to better detect opportunities for optimizations
- Both of them by enabling the compiler to issue better diagnostics
I actually
started to apply attributes for the third reason. I once accidentally introduced a bug with a refactoring: Some function for formatted logging suddenly had an argument of the wrong type. With
printf()
and friends, compilers already know their semantics and issue warnings about that, but for other functions, an attribute ("format") is needed to let the compiler know.