Enums in Pascal

Our enum type ServerState has an underlying int type. Enumerated types (enums) are data structures that allow us to define a set of named values for a variable. While some languages have built-in support for enums, many can simulate them using other features.

program EnumsExample;

uses SysUtils;

type
  ServerState = (StateIdle, StateConnected, StateError, StateRetrying);

var
  stateName: array[ServerState] of string = (
    'idle',
    'connected',
    'error',
    'retrying'
  );

function StateToString(ss: ServerState): string;
begin
  StateToString := stateName[ss];
end;

function Transition(s: ServerState): ServerState;
begin
  case s of
    StateIdle:
      Transition := StateConnected;
    StateConnected,
    StateRetrying:
      Transition := StateIdle;
    StateError:
      Transition := StateError;
  else
    raise Exception.Create('unknown state: ' + IntToStr(Ord(s)));
  end;
end;

var
  ns, ns2: ServerState;

begin
  ns := Transition(StateIdle);
  WriteLn(StateToString(ns));
  ns2 := Transition(ns);
  WriteLn(StateToString(ns2));
end.

The possible values for ServerState are defined as constants of an enumerated type. By using a mapping array, values of ServerState can be printed out or converted to strings.

In the main section, we create a ServerState variable and transition between states. If we try passing a non-ServerState value to the transition function, Pascal will ensure type safety at compile-time, preventing errors.