True C static local variable?

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?

+5
source share
2 answers

There is no direct equivalent to static variable C in Delphi

(. User1092187 ) . , , C C++. , , .

.

var
  dx: Integer;
  dy: Integer 

function UpdatePosition(x,y: Integer): Boolean;
begin
  if (x+dx < 0) or (x+dx > 640) then
    dx := -dx;
  ...
  MoveObject(x+dx, y+dy);
  ...
end;

initialization:

initialization
  dx := Trunc( Power(-1, Random(2)) );
  dy := Trunc( Power(-1, Random(2)) );

, . Delphi , , , .

type
  TPosition = class
  private class var
    dx: Integer;
    dy: Integer;
  private
    class constructor Create;
  public
    class function UpdatePosition(x,y: Integer): Boolean; static;
  end;

class constructor TPosition.Create;
begin
  dx := Trunc( Power(-1, Random(2)) );
  dy := Trunc( Power(-1, Random(2)) );
end;

class function TPosition.UpdatePosition(x,y: Integer): Boolean;
begin
  // your code
end;
+6

"Writable typed constantants" :

{$J+}
procedure abc;
const
  II: Integer = 45;

begin
  Inc(II);
  ShowMessage(IntToStr(II));
end;
{$J-}

procedure TForm1.Button1Click(Sender: TObject);
begin
  abc;
  abc;
  abc;
end;
+4

All Articles