Stage 98: Loop statement does it
Posted: Tue Mar 08, 2022 9:59 am
The new shortcut operators (see stages 96-97) allow for a more flexible and readable loop statement, so flexible in fact that SharpBASIC's count statement (aka the for-loop) has almost become superfluous and certainly "ugly" (keep in mind this is still pre-alpha stage).
Consider the following example:
The flexibility lies in the fact that the while (or until) condition can be put at the top or the bottom of the loop. In Addition, the increment or shortcut operator can be placed anywhere inside the loop, i.e. it is not bound to the condition statement. The shortcut operators also allow for steps without the need of a step or by keyword:
Finally, multiple shortcut operators may influence the iterator in a single loop:
The possibilities are almost endless. Even jump statements and labels are allowed inside the loop statement. Needless to say this should be done with care.
Of course, the basic loop remains:
Consider the following example:
Code: Select all
dim i:int;
main do
' print numbers 1 to 10
loop i = 0 do
while i < 10; i:++;
print(i);
end
end
Code: Select all
dim i:int;
main do
' print numbers 1 to 10, step 2
loop i = 0 do
while i < 10; i:+2;
print(i);
end
end
Code: Select all
dim i:int;
main do
' titius-bode law
loop i = -3 do
print((i+4)*15);
if i < 3 do
i:+3;
else do
i:*2;
end
while i <= 384;
end
end
Of course, the basic loop remains:
Code: Select all
dim n:int=1;
main do
loop do
while n < 11;
print(n);
n = n + 1; ' (or n:++)
end
end