8
votes

I am trying to define a const in Delphi (Delphi 2005 that is) that is based on other constants, but Delphi complains about it not being a constant expression. This is what my code looks like:

program myProgram;

const
  Xpoints = 20;
  Ypoints = 30;
  ArraySize = trunc(sqrt(Xpoints*Ypoints));

var
  myArray : array[1..ArraySize] of integer;

I could do ArraySize = Xpoints*Ypoints but the sqrt causes problems. The idea is that I would like the array to be sized by the constants Xpoints and Ypoints. I could do something like this:

program myProgram;

const
  sqrtXpoints = 4.472135956;
  sqrtYpoints = 5.47722557506;
  Xpoints = trunc(sqrtXpoints*sqrtXpoints);
  Ypoints = trunc(sqrtYpoints*sqrtYpoints);
  ArraySize = trunc(sqrtXpoints*sqrtYpoints);

var
  myArray : array[1..ArraySize] of integer;

taking care to slightly overestimate the square root values for the trunc. Everything will update correctly if I change sqrtXpoints or sqrtYpoints, but this approach just seems so... stupid.

As a temporary fix I can evaluate the constant myself like this:

program myProgram;

const
  Xpoints = 20;
  Ypoints = 30;
  ArraySize = 24;

var
  myArray : array[1..ArraySize] of integer;

but I don't like this because ArraySize does not automatically update if I change Xpoints or Ypoints.

It seems like the compiler should know how to evaluate a constant defined as a mathematical function of another constant at compile time for things like the example above and for even simpler things like this:

const
  pi = 4.0*arctan(1.0);

but I can't get it to accept it. Any suggestions? Thanks in advance for your help!

1
You simply cannot use functions in constant declarations.Andreas Rejbrand
The compiler won't evaluate sqrt. You could, I suppose, use a typed constant and fix it up at initialization time. You'd need a couple of VirtualAlloc calls to make that fly.David Heffernan
Another workaround option is to use a compiler which is less picky on the constant expressions (fpc).OnTheFly
@OnTheFly, I wouldn't call changing the compiler a workaround.Uwe Raabe

1 Answers

7
votes

Delphi do not allow to use most of functions in definition of constants. But you can easy solve it, just use dynamic arrays and you will be able to calculate all what you want from your code:

const
  Xpoints = 20;
  Ypoints = 30;
var
  myArray : array of integer;

procedure TForm9.FormCreate(Sender: TObject);
begin
  setlength(myArray, trunc(sqrt(Xpoints*Ypoints)));

end;