loop variable

Top  Previous  Next

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

A direct translation of a Delphi loop-variable declaration can produce a subtle error when the loop reaches the highest or lowest value representable by that variable type.

 

Consider the following Delphi function:

 

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;

 

 

A straightforward C++ translation without a stop variable would be:

 

 

bool __fastcall ToHigh()

{

    bool result = false;

    WideChar C = L'\0';  // Incorrect loop-variable type

    int I = 0;

 

    for (C = 0 /* Low(WideChar) */;

         C <= 65535 /* High(WideChar) */;

         ++C)

    {

        I = static_cast<int>(C);

    }

 

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

    return result;

}

 

 

This code results in an infinite loop. After the iteration with 'C == 65535', the expression '++C' is executed. Because a 'WideChar' cannot represent '65536', the value wraps around to '0'. The condition 'C <= 65535' consequently remains true.

 

To preserve the Delphi behavior, Delphi2Cpp changes the loop variable to a wider type:

 

 

bool __fastcall ToHigh()

{

    bool result = false;

    int C = 0;  // Corrected loop-variable type

    int I = 0;

    int stop = 0;

 

    for (stop = 65535 /* High(WideChar) */,

         C = 0 /* Low(WideChar) */;

         C <= stop;

         ++C)

    {

        I = C;

    }

 

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

    return result;

}

 

 

The wider type can represent '65536', allowing the loop condition to become false after the final iteration.

 

This check is independent of the stop-variable option. A stop variable prevents the final expression from being evaluated repeatedly, but it does not prevent the loop variable itself from overflowing.

 

Delphi2Cpp detects this situation automatically and widens the loop-variable type when required. The corresponding check is also applied to 'downto' loops when decrementing the original type below its lowest representable value could prevent correct loop termination.

 



This page belongs to the Delphi2Cpp Documentation

Delphi2Cpp home  Content