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!
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