[Issue 8185] Pure functions and pointers

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Jun 4 09:25:26 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=8185



--- Comment #40 from Denis Shelomovskij <verylonglogin.reg at gmail.com> 2012-06-04 20:27:24 MSD ---
(In reply to comment #36)
> > int f(size_t) pure;
> 
> > __gshared int tmp;
> > void g(size_t, ref int dummy = tmp) pure;
> 
> > void h(size_t a, size_t b) pure
> > {
> >    int res = f(a);
> >    g(b);
> >    assert(res == f(a)); // may fail, no guaranties by language!
> >}
> 
> Your g(b) causes h to be impure, because it accesses tmp, which is __gshared.

Yes, my mistake. Lets call "g(b, b)".

> Also, as far as eliding additional calls to pure functions, at present, they
> only occur within the same line, and I think that may only ever occur within
> the same expression (it's either expression or statement, I'm not sure which).
> So, the eliding of additional pure function calls is going to be quite rare.
> The _primary_ benefit of pure is how it enables you to reason about your code.
> You _know_ that f doesn't mess with anything other than the argument that you
> passed to it without having to look at its body at all.

No, because the assert may not pass. See below.

> Oh, and the assertion _is_ guaranteed to pass. a and res are both value types.
> Neither res nor a are passed to anything or accessed in any way other than in
> the the lines with the calls to f, and even if g were impure, and it screwed
> with whatever argument was passed as the first argument to the h call, it
> wouldn't be able to mess with the value of a, because it was already copied.

Again, assert may not pass. Were it pass, I will not write this question.
Example:
---
int f(size_t p) pure
{
    return *cast(int*) p;
}

void g(size_t p, ref size_t) pure
{
    ++*cast(int*) p;
}

void h(size_t a, size_t b) pure
{
    int res = f(a);
    g(b, b);
    assert(res == f(a)); // may fail, no guaranties by language!
}

void main()
{
    int a;
    h(cast(size_t) &a, cast(size_t) &a);
}
---

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list