Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

looking on example 1, I wonder why don't languages like C++ or D or Go just add a "pure" keyword for functions that don't modify the global environment or their arguments? this will help the optimizers a lot I imagine. and yeah, I get it that there still could be roundabout side-effects, it's not Haskell, but the compiler could just trust the programmer that he knows what he's doing when he sticks the "pure" keyword before a function definition.


> looking on example 1, I wonder why don't languages like C++ or D or Go just add a "pure" keyword for functions that don't modify the global environment or their arguments?

The function in example 1 is modifying a member variable, and there is indeed a keyword that requires functions not to modify the class they operate on: const. It's very powerful, and by a long shot my favourite feature of C++.

That said, the function in question actually has to modify a member variable.


The problem here isn't updateCachedWidth(), which indeed modifies a member variable, but deviceScaleFactor(), which doesn't. Since LLVM doesn't infer that deviceScaleFactor() leaves m_cachedWidth unmodified, it forces a reload of m_cachedWidth after the function call in case the value changed.


It was an example. Replace deviceScaleFactor with some other function that modifies, say, m_foo, and you have the same problem. And no, const+mutable is not an answer(in my example), because the function does in fact modify the class in a way important to the caller.


There is[1] a `pure` attribute in GCC extensions to C and C++:

    int square (int) __attribute__ ((pure));
But I can't say how smart is the compiler in handling those attributes.

[1] http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html


"Pure functions are functions which cannot access global or static, mutable state save through their arguments". http://dlang.org/function.html





Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: