Address of parameterless ref function

Cliff Hudson cliff.s.hudson at gmail.com
Sat Apr 9 10:51:19 PDT 2011


It looks like in the absence of an assignment of the output of g() to some
value (say int b = g()) which the compiler would insert conversion code for,
the ref is retaining some pointer semantics.  I'm guessing that because
writeln is variadic the compiler doesn't do anything with g's output (like
dereference it, convert it to an int, etc.), so you just keep getting the
pointer of 'a' back.  I don't know the internals, but I'm guessing ref is
syntactic sugar to make pointer operations appear like normal value
operations.  If you replaced (conceptually) ref int g() with int* g(), and
replace return ++a with ++a; return &a, then you'd get the output you see.

- Cliff

On Sat, Apr 9, 2011 at 9:59 AM, Timon Gehr <timon.gehr at gmx.ch> wrote:

> Whats the output of the following code supposed to be?
>
> import std.stdio;
>
> int a=0;
> ref int g(){
>    writeln("called g");
>    return ++a;
> }
>
> void main(){
>    int function() f=&g;
>    writeln(cast(int)&a);
>    writeln(f());
>    writeln(f());
>    writeln(f());
> }
>
> The output using dmd 2.052
> -144918776
> called g
> -144918776
> called g
> -144918776
> called g
> -144918776
>
> This is certainly wrong, as it includes an IMPLICIT cast from int* to int,
> but
> there are happening other strange things.
>
> How to distinguish taking the address of a call to a parameterless ref
> function from taking the address of the function itself anyways?
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20110409/c0959950/attachment.html>


More information about the Digitalmars-d mailing list