开发者

What is The Loop Variable After a For Loop in Delphi?

开发者 https://www.devze.com 2022-12-26 01:54 出处:网络
In Delphi, consider var i: integer; begin for i := 0 to N do begin { Code } end; One might think that i = N after the for loop, but does the Delphi compiler guarantee this? Can one make the assum

In Delphi, consider

var
  i: integer;

begin

  for i := 0 to N do
  begin
    { Code }
  end;

One might think that i = N after the for loop, but does the Delphi compiler guarantee this? Can one make the assumption that the loop variable is equal to its last value inside开发者_Go百科 the loop, after a Delphi if loop?

Update

After trying a few simple loops, I suspect that i is actually equal to one plus the last value of i inside the loop after the loop... But can you rely on this?


No, Delphi does not guarantee any value. Outside the loop, the variable is undefined - and IIRC the Language Guide excplicitly state so - that means that newer compiler implementations are free to change whatever value the variable may have outside the loop due to the actual implementation.


The compiler actually emits a warning if you use the loop variable after the loop, so you should consider it undefined.


I would suggest that using a while loop is clearer if you need to use the loop index after the loop:

i := 0;
while i <= N
begin
    { Code }
    i := i + 1;
end;

After that loop terminates, you know that i will be N + 1 (or greater, if N could have been less than zero).


It is even documented that the loop variable from a for loop is undefined outside the loop.

In practice: What you get from the variable varies depending on compiler settings and code complexity. I have seen changes in code push the compiler into a different optimization path, therefore modifying the value of this undefined variable.

--jeroen


As many people stated, the I variable is supposed to be undefined after the loop. In real world usage, it will be defined to the last value it had before you "break", or to N + 1 if loop run to term. That behavior cannot be relied on though, as it's clearly specified it's not meant to work.

Also, sometimes, I won't even be assigned. I encountered this behavior mostly with optimisation turned ON.

For code like this

I := 1234;
For I := 0 to List.Count - 1 do
begin
  //some code
end;
//Here, I = 1234 if List.Count = 0

So... If you want to know the value of I after the loop, it's better practice to assign it to another variable before going out of the loop.


NEVER EVER rely on the value of the for variable, after the loop.

Check your compiler output. Delphi compiler warns you about that. Trust your compiler.

  1. NEVER hide your compiler's hints and warnings with {$Warnings off}!
  2. Learn to treat the info as warnings and the warnings as errors!
  3. Optimize your code until you have ZERO hints and warnings (without violating rule 1).
0

精彩评论

暂无评论...
验证码 换一张
取 消