[fpc-pascal] Legitimate use of for and break
fpc.2021 at t-net.ruhr
Fri Jun 16 13:23:15 CEST 2023
I'm certainly not the expert in FPC's details, so maybe there'll you'll get a better answer. I just tell you my point of view.
>> It's an array with a terminator
>>string? Probably the length of the array should be set instead of
>>doing string compares every loop.
> I need to set it in the var declaration, right?
I don't quite understand this question, but of it's about the length of the array, there are two ways:
a) Statically as "VAR x: array[1..6] of string"
var x: array of string; // I prefer x: TStringArray instead, but this requires the classes unit IIRC
SetLength(x, 6); // will always declare a zero-based index, i.e. x..x
// the advantage is you can change this lateron:
SetLength(x, 7); // keeps items 0..5 and adds x
> words[ss] := '~';
> ^^^^^^^^^^^^^^^^^^^^ Is it legitimate to set elements inside a for loop?
Yes, of course. You're not allow to change the loop variable, but you can assign array values there without any problem. In fact, with larger arrays, it may even be the *only* way to do it. (Except using a different loop type like while or repeat, of course.)
Imagine you want to have x^2 for x = 0...1000:
var y: array[0..1000] of integer; x: integer;
for x:=0 to 1000 do // ; I prefer: for x := Low(y) to High(y) do
y[x] := x * x;
If you couldn't do that, you'd have to write
y := 0;
y := 1;
y := 4;
y := 9;
> if words[ss] = '~' then
> ^^^^^ IS IT legitimate to use a break (or continue) inside
> a for loop?
As far as I know, there are different opinions about this. The clear answer to whether it's *legitimate* is YES, because that's what "break" is meant for.
Whether it's elegant is a different question. In my opinion YES because it often gives better readable code than nested "if" statements inside the loop. But I've also read that using "break" is discouraged because it shows a bad choice of the loop range.
More information about the fpc-pascal