Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error defining constants in Delphi

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!

like image 949
Michael Saeger Avatar asked Aug 26 '13 20:08

Michael Saeger


1 Answers

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;
like image 73
Andrei Galatyn Avatar answered Nov 05 '22 13:11

Andrei Galatyn