Bug or logic error in if with auto?

Nick Treleaven ntrel-public at yahoo.co.uk
Mon Dec 3 06:22:27 PST 2012


On 02/12/2012 15:09, js.mdnq wrote:
> Can this be made to work in D?
>
> Error in D, x not found:
>
> if (auto x = "thing" in arr && x == 45)
> {
>
> }
>
> Works:
>
> if (auto x = "thing" in arr)
>      if (x == 45)
>      {
>
>      }

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). As 
you have shown, D's 'if' statement declaration form is perhaps not very 
useful.

About while declaration syntax, see:
http://d.puremagic.com/issues/show_bug.cgi?id=5432


More information about the Digitalmars-d mailing list