loop variable

Top  Previous  Next

What is translated > Statements > for loop's > loop variable

 

The variable that is incremented in a for loop is declared like any other variable (before Delphi 10.4) at the beginning of the function body. However, converting this declaration to C++, like the other variables, can lead to a sublime error. This is demonstrated in the following example:

 

function ToHigh: boolean;

var

  C: WideChar;

  I: Integer;

begin

  I := 0;

  for C := Low(WideChar) to High(WideChar) do

    I := Integer(C);

  result := I = Integer(High(WideChar));   // 65535

end;

 

The straight forward translation of this code - without use of a stop variable - results in:

 

bool __fastcall ToHigh()

{

  bool result = false;

  WideChar C = L'\0';       //  <=  wrong type

  int I = 0;

  I = 0;

  for(C = 0 /*# Low(WideChar) */; C <= 65535 /*# High(WideChar) */; C++)

  {

    I = ((int) C);

  }

  result = I == 65535 /*# High(WideChar) */;   // 65535

  return result;

}

 

However, executing this code will result in an infinite loop, because in C++ the loop is only broken after the loop variable has a value higher than the maximum value of a wide character variable "High(WideChar)". Therefore the type of the loop variable must be changed so that it can get this value.

 

 

bool __fastcall ToHigh()

{

  bool result = false;

  int C = 0;               //  <=  corrected type

  int I = 0;

  int stop = 0;

  I = 0;

  for(stop = 65535 /*# High(WideChar) */, C = 0 /*# Low(WideChar) */; C <= stop; C++)

  {

    I = C;

  }

  result = I == 65535 /*# High(WideChar) */;   // 65535

  return result;

}

 

Delphi2Cpp checks this case and automatically changes the variable type during code translation; also accordingly for the "downto" case.

 

 

 

 

 

 

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content