1. Home
  2. Computing & Technology
  3. Delphi Programming

How to Declare and Initialize Constant Arrays in Delphi

By , About.com Guide

In Delphi, arrays allow a developer to refer to a series of variables by the same name and to use a number (an index) to tell them apart.

In most scenarios, you declare an array as a variable - thus allowing for array elements to be changed at run-time.

Sometimes, you need to declare a constant array - a read-only array. You cannot change the value of a constant or a read-only variable. Therefore, while declaring a constant array you have to initialize it.

Here are a few examples of declaring and initializing constant arrays in Delphi:

type
   TShopItem = record
     Name : string;
     Price : currency;
   end;

const
   Days : array[0..6] of string =
   (
     'Sun', 'Mon', 'Tue', 'Wed',
     'Thu', 'Fri', 'Sat'
   ) ;

   CursorMode : array[boolean] of TCursor =
   (
     crHourGlass, crSQLWait
   ) ;

   Items : array[1..3] of TShopItem =
   (
     (Name : 'Clock'; Price : 20.99),
     (Name : 'Pencil'; Price : 15.75),
     (Name : 'Board'; Price : 42.96)
   ) ;
The above code declares and initializes three constant arrays, named: "Days", "CursorMode" and "Items".

"Days" is a string array of 6 elements. Days[1] returns the "Mon" string.

"CursorMode" is an array of two elements, where by declaration CursorMode[false] = crHourGlass and CursorMode[true] = crSQLWait. "cr*" constants can be used to change the current screen cursor.

var
   isDatabaseOperation : boolean

begin
   isDatabaseOperation := true;

   //changes the cursor to crSQLWait
   Screen.Cursor := CursorMode[isDatabaseOperation];

"Items" defines an array of 3 TShopItem records.

Note: trying to assign a value for an item in a constant array raises the "Left side cannot be assigned to" compile time error, as in:

Items[1].Name := 'Watch'; //will NOT compile

Delphi tips navigator:
» How to Highlight Non-Focused DBGrid Selected Row
« Enumerating and Playing System Sounds from Delphi code

More Delphi Programming Quick Tips
Explore Delphi Programming
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. Delphi 2006 Tips
  7. How to Declare and Initialize Constant Arrays in Delphi

©2009 About.com, a part of The New York Times Company.

All rights reserved.