Feature request: Specify array indices explicitly in array initializers

Summary

Currently (FPC 3.2.2) the language only have the following form of static array initialization:

const
  example: array[0..3] of Integer = (123, 456, 789);

The problem with it is that if we have an enumeration type as an index and that type has a lot of values, this quickly becomes hard to maintain and error-prone. Consider this snippet:

type
  TState = (
    StateA0,
    StateB1,
    StateC2,
    StateD3,
    StateE4,
    StateF5,
    StateG6,
    StateH7,
    StateI8,
    StateJ9
  );

const
  NextState: array[TState] of TState = (
    StateE4,
    StateA0,
    StateC2,
    StateC2,
    StateG6,
    StateE4,
    StateA0,
    StateI8,
    StateG6,
    StateI8
  );

Since the source and result states are not clearly specified next to each other, it becomes very easy to mess up the correct mapping between them when adding and removing values.

What I would like to propose is to allow arbitrary ordering of elements by explicitly specifying the index to which the value is assigned:

const
  example: array[0..3] of Integer = (
    0: 123,
    2: 789,
    1: 456
  );

This will drastically improve the usability and applicability of initializers, as it will allow them to be used without fear for things such as state machines and sparse graphs. Now the only sane way to specify them is an initialization function or a constructor, which has at least the following disadvantages:

  • this is run-time instead of compile-time and thus adds unnecessary overhead;
  • this causes the array to be defined as var even if it never actually changes and is de facto const;
  • if the array should contain not values ​​of elementary types, but records, then this requires EVEN more code to set values ​​for fields, since the language currently lacks the ability to express values of complex types, like compound literals in C or temporary types in FreeBASIC.

A similar syntax already exists for initializing records, but it differs in that members there are separated with a semicolon instead of a comma. Note that this feature will also allow individual values ​​to be omitted from array initializers, just as it's already permitted for records.

Relevant 3rd party information

Edited by Dmitry D. Chernov