Is it possible to declare a const of an array in BOTH Delphi and FreePascal without having the elements be constants?

StackOverflow https://stackoverflow.com/questions/749258

Question

A long time ago I remember I could do this in Turbo Pascal 7.

Maybe I'm wrong and it's something I need to clarify, but is it possible to declare an array of strings as a constant?

If not what's the option/workaround.

What I have now is:

type
  TStates = (sOne, sTwo, sThree);
var
  TArrayOfString: array [sOne..sThree] of string = 
     ('State one', 'State two', 'State three');

but would want to replace that var with a const.

Thanks

Edit 1: Added some more code to clarify my question.

Was it helpful?

Solution

Just replacing var with const is perfectly legal:

const
  TArrayOfString: array [1..3] of string =
     ('String one', 'String two', 'String three');

I am curious why your identifier name starts with a T though. Were you trying to define a type like this:

type
  TArrayOfString = array [1..3] of string;
const
  MyArrayOfString: TArrayOfString =
     ('String one', 'String two', 'String three');

You cannot have a variable length array (AFAIK) as a const, nor can you have it of an undefined type.

This is with Delphi 2009. YMMV with FreePascal.

OTHER TIPS

In old day pascal/delphi when you wrote:

const 
  A : Integer = 5;

You did not define a constant, but an initialized variable.

You can define without problem:

const
  A : array [1..2] of string = ('a', 'b');

But the strings have to be constants too. They need to be known at compile time.

The same goes for:

var
  A : array [1..2] of string = ('a', 'b');

So you can't write:

var
  B : string = 'hi';
  A : array [1..2] of string = (B, 'b');

Because B is a var. But you can write:

const
  B = 'hi'; // Even a typed constant does not work.

var
  A : array [1..2] of string = (B, 'b');

Note that the option: "Assignable typed constants" (default false) is provided to create the old time typed constants that can be assigned. It is just there for backwards compatibility, because you really want your constants to be constant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top