True C static local variable replacement?

一曲冷凌霜 提交于 2019-12-10 13:29:00

问题


just trying to achieve similar functionality of C/C++ static local variables in ObjectPascal/Delphi. Let's have a following function in C:

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);
    ...
}

Equivalent ObjectPascal code using typed constants as a static variable replacement fails to 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 Constant expression expected

So is there some way for a one-time pass initialized local variable ?


回答1:


There's no direct equivalent of a C static variable in Delphi.

A writeable typed constant (see user1092187's answer) is almost equivalent. It has the same scoping and instancing properties, but does not allow the one-time initialization that is possible with a C or C++ static variable. In any case it is my opinion that writeable typed constants should be shunned as a quaint historical footnote.

You can use a global variable.

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;

You have to do the one-time initialization in the initialization section:

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

Of course this make a mess of the global namespace unlike the limited scope of a C static variable. In modern Delphi you can wrap it all up in a class and use a combination of class methods, class vars, class constructors to avoid polluting the global namespace.

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;



回答2:


Enable "Writable typed constants":

{$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;


来源:https://stackoverflow.com/questions/8463604/true-c-static-local-variable-replacement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!