"for" statement issue

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 21 07:16:26 PDT 2016


On 10/21/16 8:34 AM, Andrei Alexandrescu wrote:
> I got a question about what happens with this code:
>
> int j;
> for({j=2; int d = 3; } j+d<7; {j++; d++;}) {
> }
>
> My first instinct was that that won't compile but it surprisingly does.
> And it loops forever.
>
> So the grammar according to
> https://dlang.org/spec/grammar.html#ForStatement is:
>
> ForStatement:
>     for ( Initialize Testopt ; Incrementopt ) ScopeStatement
>
> Initialize:
>     ;
>     NoScopeNonEmptyStatement
>
> NoScopeNonEmptyStatement:
>     NonEmptyStatement
>     BlockStatement
>
> NonEmptyStatement goes over a bunch of odd places such as case statement
> and default statement. And then BlockStatement is the matched case:
>
> BlockStatement:
>     { }
>     { StatementList }
>
> So it seems we have another case in which "{" "}" do not introduce a
> scope. Fine. The real problem is with the increment part, which is an
> expression. The code { j++; d++; } is... a lambda expression that never
> gets used, which completes a very confusing sample.
>
> What would be a good solution to forbid certain constructs in the
> increment part of a for statement?

How about in general forbidding lambda statements that aren't called or 
used anywhere?

-Steve


More information about the Digitalmars-d mailing list