views:

436

answers:

2

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.

+3  A: 

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.

Gamecat
You still do, if {$J+} is set.
mghie
Yes that's similar to enable assignable typed constants (atc's). But you could argue if it's good to do that ;-).
Gamecat
+8  A: 

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.

Jim McKeeth
You're right about the **T** being odd. I must change that in the future.
Gustavo Carreno
What do you say about the new code? You can see that it's a Dweetta issue here ;)
Gustavo Carreno
Works for new code too. I use it all the time. You can replace the integers with enumerated types no problem.
Jim McKeeth
Looks like I had the wrong mode in FPC and that's why it wasn't working for me.
Gustavo Carreno