purity and memory allocations/pointers
H. S. Teoh
hsteoh at quickfur.ath.cx
Sat Aug 3 12:24:08 PDT 2013
On Sat, Aug 03, 2013 at 09:07:47PM +0200, Meta wrote:
> On Saturday, 3 August 2013 at 16:47:52 UTC, Timon Gehr wrote:
> >On 08/03/2013 05:59 PM, monarch_dodra wrote:
> >>One last question: Pointers.
> >>
> >>int get(int* p) pure
> >>{
> >> return *p;
> >>}
> >>
> >>void main()
> >>{
> >> int i = 0;
> >> auto p = &i;
> >> get(p);
> >>}
> >>
> >>Here, get, to me, is obviously not pure, since it depends on the
> >>state of the global "i". *Where* did "get" go wrong? Did I simply
> >>"abusively" mark get as pure? Is the "pure" keyword's guarantee
> >>simply "weak"?
> >>...
> >
> >Yes, it's weak.
>
> It depends on whether you think a pointer dereference is pure or not
> (I don't know the answer). That aside, as long as get doesn't modify
> the value at *p or change what p points to, this is strongly pure
> (i.e., the academic definition of purity).
I think a pointer dereference is weakly pure. Consider this:
int func1(int x) pure {
int scratch = x+1;
func2(&scratch);
return scratch;
}
void func2(int* x) pure {
*x = 1;
}
Clearly, func1 can be strongly pure, because its input will never change
based on any global state, in spite of the fact that func2 is
dereferencing pointers. Therefore, func2 is (should be) weakly pure.
Now consider this:
void func2(int* x) pure {
*x = 1;
}
int y = 2;
void main() {
func2(&y);
}
Can func2 still be said to be weakly pure? I say yes, because it cannot
access global that that main() isn't already passing in! It is main
that's impure, because it's the one that handed a reference to a global
to func2. If we move the definition of y inside main, then main could be
strongly pure.
Which leads us to conclude that the reason main is impure is because
it's referencing a non-local variable when it took the address of y. The
act of taking addresses and dereferencing pointers does not make code
impure; it merely makes them weakly pure as opposed to strongly pure.
And weakly pure functions are callable from strongly pure functions,
because any changes effected through pointers / references / whatever
will never escape the scope of the strongly pure function (the strongly
pure function isn't allowed to take an address of a non-local variable,
so the weakly pure function will never be able to change anything
outside). The outside world will never notice the difference.
T
--
Designer clothes: how to cover less by paying more.
More information about the Digitalmars-d
mailing list