Pure functions and pointers (yes, again)

Jonathan M Davis jmdavisProg at gmx.com
Wed Jul 4 01:20:52 PDT 2012


On Wednesday, July 04, 2012 11:59:10 Denis Shelomovskij wrote:
> Since issue 8185 has been closed, I'm still very confused. I just
> understood that endless discussion doesn't result in anything.
> 
> See example from http://d.puremagic.com/issues/show_bug.cgi?id=8185#c40
> ---
> 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);
> }
> ---
> 
> Jonathan M Davis (whose documentation correcting pull closed the issue)
> told me that this code result in undefined behaviour. What _exectly_
> language rule this violates? I don't see this rule, but if there is no
> such rule, how can we treat anything as strongly pure function?

You're violating the type system. You've claimed that a size_t is a pointer by 
casting it to one and then operating on it as if it were one. Whether the 
value was originally a pointer or not is irrelevant. You've lied to the 
compiler about the type, which means that you've subverted the type system, 
and it's up to _you_ to guarantee that the guarantees that the compiler is 
supposed to be making hold. The compiler has to use the type system to make 
its gurantees, so if you lie to it about types, it will make incorrect 
assumptions, you'll end up with wrong code, and it'll be your fault.

It's like with const. Don't cast away const and then modify the variable. It's 
undefined behavior. Don't do it. You're lying to the compiler about types, and 
it bases its guarantees on types. So, if you've lied to it, _of course_ it's 
going to break.

D is a systems language, so you can do really dirty things in @system code if 
you need to, but don't expect the compiler to magically figure out what you're 
doing when you're lying to it through casts.

- Jonathan M Davis


More information about the Digitalmars-d mailing list