Regurgitated proposal: Make loop conditions part of the body's scope

Robert Fraser fraserofthenight at gmail.com
Wed Aug 1 14:00:10 PDT 2007


downs Wrote:

> I realize this has been requested before, by me and a few others, gained the votes of a significant 
> amount of people here, been completely ignored by Walter (no offense meant, I know he can't read 
> every proposal), you know how it goes. The reason I'm bringing it up again is that it could 
> potentially, and implicitly, help (or even completely) fix a quite serious bug I discovered this 
> morning.
> 
> To recap: the proposal is to make the parameter ("()") part of some common constructs such as 
> while, do/while and with (I'll get to that in a second) part of the scope of the actual loop body - 
> this would allow, for instance, checking the value of an inner variable in the condition of a 
> do/while loop.
> Disadvantages: it breaks compatibility with C++ in cases which are forbidden anyway (shadowing 
> declarations). .. That's all I can think of. As far as I know, it doesn't change the behavior of 
> existing code.
> 
> Now, for the bug.
> Consider the following example program.
> 
> scope class test { this() { writefln("this"); } ~this() { writefln("~this"); } }
> void main() {
>          writefln("Pre");
>          with (new test) { writefln("Inside With"); }
>          writefln("Post");
> }
> 
> What would be expected: Pre  this  Inside With  ~this  Post.
> What happens: Pre  This  Inside With  Post  ~this.
> Okay, I thought, so the new test is in the outside scope. Sucks, but workable. I changed it to
> 
> 	{ with (new test) { writefln("Inside With"); } }
> 
> ...
> I got the same results.
> Turns out constructing an instance of a scoped class as the parameter of a with construct makes the 
> compiler COMPLETELY ignore the scope.
> And I can't help thinking, if the with loop's parameters were part of the inner scope, that bug 
> _probably_ wouldn't have happened. Which is why I'm holding off on a bug report until there's some 
> feedback on what the compiler should do in this situation.
> 
> With greetings and stuffies,
>   --downs

This is something I've been secretly lusting for for a while (in Java). I especially hate having to declare _and initialize_ do/while conditions outside the loop.

do
{
    String line = reader.nextLine();
    [...]
} while(null != line);

... is much prettier than...

String line = null;
do
{
    line = reader.nextLine();
    [...]
} while(null != line);

Of course, you don't need the initializer in D, but it still requires variables be declared outside the scope.So this gets my vote.

You should still file a bug about the with statement thing anyway.



More information about the Digitalmars-d mailing list