for loop's

Top  Previous  Next

What is translated > Statements > for loop's

 

In Delphi there are for-loops where a variable is incremented or decremented to or down to a special value and there are for-in loops. For the first kind of loops the for-loop parameters are evaluated only once, before the loop runs. This complicates a correct translation to C++ a little bit. The number of loops in the following example is determined by the variable n:

 

procedure test;

var

  I, n : Integer

begin

  n := 10;

  for I:=1 to n do 

  begin

    DoSomething;  

    n := 11;

  end;

end;

 

A straightforward translation of this code would be;

 

int I = 0, n = 0;

n = 10;

for ( I = 1; I <= n; I++)

{

  DoSomething();

  n = 11;

}

 

However, in C++ an additional loop would be executed, because n is changed in the loop and the number of loops is recalculated with this new value. Therefore a correct translation has to remember the original loop count like in the following code:

 

int I = 0, n = 0;

n = 10;

for (int stop = n, I = 1; I <= stop; I++)

{

  DoSomething();

  n = 11;

}

 

 

Delphi2Cpp can produce both code variants, depending on the option to Use "stop" variable in for-loop or not..

Delphi2Cpp also checks the type of the loop variable to avoid a sublime error.



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content