Show: Object Pascal C++
Display Preferences

W1037 FOR-Loop variable '%s' may be undefined after loop (Object Pascal)

From Appmethod Topics
Jump to: navigation, search

Go Up to Error and Warning Messages (Object Pascal) Index

This warning is issued if the value of a for loop control variable is used after the loop.

You can only rely on the final value of a for loop control variable if the loop is left with a goto or exit statement.

The purpose of this restriction is to enable the compiler to generate efficient code for the for loop.


program Produce;
(*$WARNINGS ON*)

function Search(const A: array of Integer; Value: Integer): Integer;
begin
  for Result := 0 to High(A) do
    if A[Result] = Value then
      break;
end;

const
  A : array [0..9] of Integer = (1,2,3,4,5,6,7,8,9,10);

begin
  Writeln( Search(A,11) );
end.

In the example, the Result variable is used implicitly after the loop, but it is undefined if we did not find the value - hence the warning.


program Solve;
(*$WARNINGS ON*)

function Search(const A: array of Integer; Value: Integer): Integer;
begin
  for Result := 0 to High(A) do
    if A[Result] = Value then
      exit;
  Result := High(a)+1;
end;

const
  A : array [0..9] of Integer = (1,2,3,4,5,6,7,8,9,10);

begin
  Writeln( Search(A,11) );
end.

The solution is to assign the intended value to the control variable for the case where we don't exit the loop prematurely.

Personal tools
In other languages