Ada: Enumeration
An enumeration type is a set of named literals with a defined order. In Ada, enumerations are full-fledged types — not integer constants wearing names — so a Day cannot be passed where a Month is expected, and adding a literal later makes the compiler find every incomplete case.
Declaring Enumerations
with Ada.Text_IO; use Ada.Text_IO;
procedure Enum_Demo is
type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
Today : Day := Wed;
begin
-- order is meaningful: Wed > Mon, and succ/pred walk the sequence
if Today > Fri then -- comparison uses declaration order
Put_Line ("weekend");
end if;
Put_Line (Day'Image (Today)); -- "WED" — the literal's name as text
Put_Line (Day'Pos (Today)'Image); -- "2" — position, first literal is 0
end Enum_Demo;
Attributes make enumerations self-describing: 'First / 'Last give bounds, 'Succ / 'Pred walk neighbors, 'Image / 'Value convert to and from text. There is no need for the hand-written toString tables C programs grow.
Subtypes Restrict Ranges
A subtype of an enumeration names a legal window — perfect for weekdays, work modes, or state subsets:
procedure Weekday_Demo is
type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
subtype Weekday is Day range Mon .. Fri;
D : Weekday := Thu; -- legal
-- D := Sun; -- compile error: Sun is not in Mon .. Fri
begin
null;
end Weekday_Demo;
Character and Boolean Are Enumerations
The two predefined types you use daily are themselves enumerations — Boolean is (False, True) and Character lists all 256 values. This is why they get 'Pos/'Val, ordering, and case coverage for free:
with Ada.Text_IO; use Ada.Text_IO;
procedure Case_Enum is
type State is (Idle, Running, Stopped, Failed);
S : constant State := Running;
begin
case S is
when Idle | Running => Put_Line ("system operational");
when Stopped => Put_Line ("system halted");
when Failed => Put_Line ("system degraded");
-- all literals covered; no "when others" required
end case;
end Case_Enum;
Coverage is the payoff: if a future revision adds a Maintenance state, every case over State fails to compile until it is handled. The type change propagates through the codebase as errors, not as silent fall-throughs.
Representation — When It Must Match Hardware
By default, the compiler chooses the internal representation. When interfacing with hardware or protocols, specify it explicitly:
procedure Hardware_Demo is
type Level is (Low, Mid, High);
for Level use (Low => 0, Mid => 4, High => 9); -- exact wire values
begin
null;
end Hardware_Demo;
Next: Arrays.