pascalfreepascalturbo-pascal

What is that the Error of Illegal assignment and how to correct it?


procedure tri_selection(t: tab; n: Integer);
var
 i, j, min, aux: Integer;
begin

  for i := 1 to n - 1 do
  begin

    min := i;

    for j := i + 1 to n do
      if t[j] < t[min] then
        j := min;

    if min <> i then
    begin
      aux := t[i];
      t[i] := t[min];
      t[min] := aux;
    end;

  end;

end;

That's supposed to be a correct and well-known code to arrange integers from inferior to superior but compiler still insists saying "illegal assignment to for loop 'j' variable".

What's the problem?


Solution

  • The problem is here:

    for j := i + 1 to n do
      if t[j] < t[min] then
        j := min;                      // <-- Not allowed to assign to FOR loop variable j
    

    You are not allowed to assign to the for loop variable.

    Perhaps you meant to write

    for j := i + 1 to n do
      if t[j] < t[min] then
        min := j;