Bug or logic error in if with auto?

deadalnix deadalnix at gmail.com
Fri Dec 7 10:59:36 PST 2012


On Friday, 7 December 2012 at 14:21:51 UTC, Nick Treleaven wrote:
> On 03/12/2012 14:22, Nick Treleaven wrote:
>> Most programmers would probably just pollute the existing 
>> scope:
>>
>> auto x = "thing" in arr;
>> if (x && *x == 45)
>> {
>>     ...
>> }
>>
>> I expect this is because wrapping the above in {} for a new 
>> scope is
>> just too ugly, introducing more nesting and indentation.
>>
>> It would be nice if there was a way of introducing a new scope 
>> just for
>> a declaration and the next statement, something like:
>>
>> with auto x = "thing" in arr:
>> if (x && *x == 45)
>> {
>>     // x is still visible here
>> }
>>
>> That would overload 'with' with a different meaning, but would 
>> be clear
>> enough IMO. It would be useful with other constructs like 
>> while, do,
>> foreach, etc. I think it would be more elegant than allowing a
>> declaration clause in all constructs (like the 'for' statement 
>> has).
>
> The above syntax was inspired from Tove and Tommi's existing 
> solution (I couldn't find the link earlier):
> http://forum.dlang.org/post/nyhpuaoxkeunwqongfyk@forum.dlang.org
>
> The idea was to use a Tuple to wrap the new variable:
>
> with (Tuple!(int, "a")(getInt()))
> if (a > 9)
>     ...
>
> I've now improved on this syntax using opDispatch and opAssign 
> so we can write:
>
> with (wrap.a = getInt())
> if (a > 9)
>     ...
>
> Whether using this in real code is good practice or not may be 
> debatable ;-)
>
> Code:
> http://dpaste.dzfl.pl/4dbefd84

That is really an interesting idea.


More information about the Digitalmars-d mailing list