Forum > General

Nested procedure and for variable

(1/2) > >>

BenLaz:
Hello,

I have a small question :

In a for statement, the variable cannot be affected by a direct affectation or by passing it to a procedure as var parameter (but it can me modified via its adress wich the compiler cannot detect).

But in the case of a nested procedure, you can modify the variable if theis way :

procedure Test;
var
  iCount : Integer;
    procedure NestedProc;
    begin
      iCount := 10000;
    end; 
begin
  for iCount := 0 to 10 do
  begin
    NestedProc;
  end;
end;

Does anyone know if it's really "legal" to do this and if delphi autorize that construction (i don't have a Delphi at home so i'll check later at work).

Best regards

marcov:
It seems to work with both Delphi and FPC, but I don't know if that because this code is simple or not. (it is possible that the compilers decide to force the loopvar to a variable, essentially changing the for to a while, and then it would be safe).

However, working around errors like this is not smart. If it is forbidden, there is a good reason. Use break or rewrite the for loop using a different looping concept (while/repeat)

howardpc:
'Legal' in the sense of 'compilable', yes. But completely pointless. A hack to avoid.
Why would you want a for loop declared to run for 11 iterations that only makes one iteration?
If you want to fiddle with loop counters, much better to use a while or repeat construct.

typo:
Do you complain that the compiler did not make a complete work? Should it make it? Change the counter of a for loop is not legal for the language.

BenLaz:
Thank you for your answsers.

In fact my question is just theorical, i don't want to use this kind of construction; but i just want to know why the compiler doesn't complain about that.

Best regards

Navigation

[0] Message Index

[#] Next page

Go to full version