HomeDelphiDelphi Error – E2081 Assignment to FOR-Loop variable ‘%s’

Delphi Error – E2081 Assignment to FOR-Loop variable ‘%s’

Delphi Compiler Error

E2081 Assignment to FOR-Loop variable ‘%s’

Reason for the Error & Solution

It is illegal to assign a value to the for loop control variable inside the for loop.

If the purpose is to leave the loop prematurely, use a break or goto statement.

program Produce;

var
  I: Integer;
  A: array [0..99] of Integer;
begin
  for I := 0 to 99 do begin
    if A[I] = 42 then
      I := 99;
  end;
end.

In this case, the programmer thought that assigning 99 to I would cause the program to exit the loop.

program Solve;

var
  I: Integer;
  A: array [0..99] of Integer;
begin
  for I := 0 to 99 do begin
    if A[I] = 42 then
      Break;
  end;
end.

Using a break statement is a cleaner way to exit out of a for loop.

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

Delphi Compiler Error X2421 Imported identifier ‘%s’ conflicts with ‘%s’ in ‘%s’ Reason for the Error & Solution This occurs...
Delphi Compiler Error X2367 Case of property accessor method %s.%s should be %s.%s Reason for the Error & Solution No...
Delphi Compiler Error X2269 Overriding virtual method ‘%s.%s’ has lower visibility (%s) than base class ‘%s’ (%s) Reason for the...