On Friday, 21 October 2016 at 12:34:58 UTC, 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?
Thanks,
Andrei
I am the one who raised the question. I am n00b when it comes to
D language (I just started reading about it a couple of days ago)
and I tried the above mentioned code expecting that either the
variables j and d get incremented accordingly or at least
I would get a compilation error. Instead, the program compiles
and when run it sticks
into an infinite loop. I haven't read anything about lambda
functions in D, but the
current outcome is very confusing for a beginner like myself.
Thanks,
RazvanN