Hi Marc,
I’m curious that you didn’t say that the combination of assignment and comparison isn’t legal, since the problem isn’t the inline variable declaration but the use of an assignment within the conditional expression:
i.e. this doesn’t compile, even when all variables involved are pre-declared:
while ((length := instream.read(buffer)) > 0)
Should this compile ? Will this ever be supported ? (personally I don’t think it should)
I can see a way to make such a loop more explicit. The objective is to initialise a condition variable at the commencement of a loop (initial and repeated) and to loop only if and while that variable meets and continues to meet a condition. This could be achieved by combining a for
initialisation clause with a while
conditional loop.
This would be a distinct syntax, separated from a regular for
loop by the lack of a to
clause. In this case, the resulting loop would be:
for length := instread.read(buffer) while length > 0 do
begin
end;
Though not as compact as the C-style combined assignment and comparison, this does simplify the loop structure that is otherwise required with the repeat
construct whilst retaining the fact that the two components (assignment and condition) are a key component of the loop.
This would also allow richer combinations of loop initialisation and condition, beyond simply testing a value assigned in the condition:
for length := instread.read(buffer)
while (length > 0) and (buffer.Contains('foo')) do
begin
end;
The syntactic similarity to the otherwise required repeat
loop is striking, especially if you format it to emphasise the similarity:
repeat length := instread.read(buffer)
if (length > 0) and (buffer.Contains('foo')) then
begin
end;
until (length = 0) or (not buffer.Contains('foo'));
Note however that repeat
requires the loop condition to be duplicated, occurring once within the loop and then again, inverted, as the loop condition. ime duplication of conditions is a common cause of bugs, especially where logic inversion is involved and required. True, this could be avoided by a diligent developer by introducing a loop control boolean, but a for .. while
grammar eliminates the need for this and would be even cleaner, imho:
Just putting it out there. 