for loop's

Top  Previous  Next

What is translated > Statements > for loop's

Delphi supports two kinds of for loops:

 

Counter-based loops using to or downto
for-in loops that iterate over the elements of a collection

 

In a counter-based Delphi loop, the initial and final expressions are evaluated exactly once, before the loop starts. In C#, however, the loop condition is evaluated before every iteration. This difference requires special handling during translation.

 

In the following example, the original value of n determines the number of iterations:

 

procedure Test;

var

  I, n: Integer;

begin

  n := 10;

 

  for I := 1 to n do

  begin

    DoSomething;

    n := 11;

  end;

end;

 

A straightforward translation would be:

 

int I = 0;

int n = 0;

 

n = 10;

 

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

{

    DoSomething();

    n = 11;

}

 

This translation does not preserve the Delphi behavior. In C#, the condition I <= n is evaluated before every iteration. Because n is changed to 11 inside the loop, C# executes an additional iteration.

 

To preserve the Delphi semantics, the original final value must be stored before the loop starts:

 

int I = 0;

int n = 0;

 

n = 10;

int stop = n;

 

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

{

    DoSomething();

    n = 11;

}

 

Delphi2C# can generate either form, depending on the Use "stop" variable in for-loop option.

 

Delphi2C# also checks whether the type of the loop variable can safely represent the value required to terminate the generated C# loop. If necessary, it changes the loop variable to a wider integral type. See Loop Variable Type for details.



This page belongs to the Delphi2C# Documentation

Delphi2C# home  Content