"for" statement issue

Andrei Alexandrescu via Digitalmars-d digitalmars-d at puremagic.com
Fri Oct 21 05:34:58 PDT 2016


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?


Thanks,

Andrei


More information about the Digitalmars-d mailing list