Ref local variables?

Ben Davis entheh at cantab.net
Wed Jan 11 01:22:59 PST 2012


What about the semantics here?

alias MapTile tile=map[y*w+x];
x++;
tile.id=something;

Personally I'd find 'ref' more intuitive since it doesn't have that 
question. Not that I'd object to alias ALSO being supported.

I'm probably not actually going to change any of those variables in my 
case, so if I had to use alias, I'd just want to be sure that the common 
subexpression elimination can pick it up. (My case is actually 3D fwiw.)

Note that this is already supported (apologies if I've got the syntax 
slightly wrong):

foreach (i, ref tile; map) { ... }

That's a local variable too. It could have instead been defined such 
that "tile" is an alias for "map[i]", but that would be a little strange.

On 11/01/2012 08:18, Gor Gyolchanyan wrote:
> I think that would introduce a big potential for bugs. Can't give you
> an example, but I have a hunch :-)
>
> I think alias is better, since ref doesn't change its target and thus
> need not be evaluated at run-time. In fact, I think alias should work
> for any sort of expression. In this case one of D's mottos will be
> "Too big? Alias it!".
>
> On Wed, Jan 11, 2012 at 8:16 AM, Robert Jacques<sandford at jhu.edu>  wrote:
>> On Tue, 10 Jan 2012 21:55:53 -0600, Nick Sabalausky<a at a.a>  wrote:
>>
>>> "Ben Davis"<entheh at cantab.net>  wrote in message
>>> news:jeinah$2pnj$1 at digitalmars.com...
>>>>
>>>> Hi,
>>>>
>>>> Please excuse the cross-post with D.learn. People have been helpful there
>>>> with workarounds, but I'm bringing it here in the hope that we can
>>>> discuss
>>>> a language enhancement.
>>>>
>>>> So - could support for 'ref' local variables be added, or is there a
>>>> reason not to? I want to write something like:
>>>>
>>>> MapTile[] map;    // It's a struct
>>>>
>>>> ref MapTile tile=map[y*w+x];
>>>> tile.id=something;
>>>> tile.isWall=true;
>>>> someFunctionThatTakesRefMapTile(tile);
>>>>
>>>
>>> I *really* want the ability to do that sort of thing, although I think it
>>> should be an alias rather than a ref variable:
>>>
>>> MapTile[] map;    // It's a struct
>>>
>>> alias map[y*w+x] tile;
>>> tile.id=something;
>>> tile.isWall=true;
>>> someFunctionThatTakesRefMapTile(tile);
>>
>>
>> Would making pointers implicitly convert to ref parameters suffice? i.e.
>> make
>>
>>     void foo(ref int x) { x++; }
>>
>>     int x = 5;
>>     auto y =&x;
>>     foo(y);
>>
>> valid D code?
>
>
>



More information about the Digitalmars-d mailing list