just trying to achieve the similar functionality of static local C / C ++ variables in ObjectPascal / Delphi. Let C have the following function:
bool update_position(int x, int y)
{
static int dx = pow(-1.0, rand() % 2);
static int dy = pow(-1.0, rand() % 2);
if (x+dx < 0 || x+dx > 640)
dx = -dx;
...
move_object(x+dx, y+dy);
...
}
The equivalent ObjectPascal code using typed constants as a replacement for a static variable will not compile:
function UpdatePosition(x,y: Integer): Boolean;
const
dx: Integer = Trunc( Power(-1, Random(2)) ); // error E2026
dy: Integer = Trunc( Power(-1, Random(2)) );
begin
if (x+dx < 0) or (x+dx > 640) then
dx := -dx;
...
MoveObject(x+dx, y+dy);
...
end;
[DCC Error] test_f.pas (332): E2026 Expected constant expression
So, is there a way for an initialized local variable with a single pass?
source
share