[fpc-pascal] private integer is an illegal counter variable
Frank Peelo
f26p at eircom.net
Fri Nov 27 22:52:30 CET 2009
Jonas Maebe wrote:
>
> On 27 Nov 2009, at 15:49, Juha Manninen wrote:
>
>> If I define a private integer:
>>
>> TDemo = class(TCustomApplication)
>> private
>> i: integer;
>> ...
>>
>> and in a protected method I use it:
>> for i := 0 to List.Count - 1 do
>> ...
>>
>> then I get an error:
>> Error: Illegal counter variable
>>
>> Moving it to method's var section helps.
>> Method's var section is also better place for it in general, but still it
>> should be legal to use a private member as counter var.
>
> The reason is that a for-loop tries to make a number of reasonable
> guarantees that the counter variable cannot be modified during the loop.
> E.g., direct assignments to a counter variable are forbidden inside the
> loop (except in TP-mode). If you use a private field, then any method of
> that class called in the body of the loop can easily (accidentally)
> change the value of the counter variable, completely messing up the loop.
In any case, why would one want a loop counter to have any more than the
minimum possible scope? Why would one want it to be a class data member
at all? Surely it would be far better/neater/more elegant, if it is used
by methods, to pass it as a parameter?
FP
More information about the fpc-pascal
mailing list