Skip to content
LumenaryAcademy
Foundations 55 min

Strong types and control flow

Integer, enumeration, modular and real types with ranges of your choosing, subtypes that narrow them, and Ada's if, case and loop statements.

Code tested · 4AI-draftedAwaiting review by a computer scientist

Your guides: Chloe · The Designer, Margaret · The Profiler, Gideon · The Language Lawyer

MotivationH

Types that mean something

In 1999 NASA lost the Mars Climate Orbiter because one piece of ground software produced thruster data in imperial units while another expected metric units. Both programs handled "a number"; nothing in their code said which kind of number. Mistakes like this are not exotic. A function that takes a width and a height in that order will, sooner or later, be called with a height and a width. A counter of passengers will be added to a floor number. An array index will be used for the wrong array.

Most languages give you a handful of built-in numeric types and leave the meaning in variable names and comments. Ada's central idea is to let you declare your own types for the quantities in your problem, with the exact range of values that make sense, and to have the compiler keep them apart. You declare that a floor is a whole number from -2 to 40 and that a passenger count runs from 0 to 12; the compiler then refuses to add one to the other, and the run-time system raises an exception the moment a floor becomes 41.

This lesson covers Ada's scalar types, the ones whose values are single numbers or names, and the statements that make decisions and repeat work. They are simple constructs, but they are where Ada's way of thinking starts.

DefinitionsH

Types, subtypes and ranges

Definition— Type

A type is a set of values together with the operations allowed on them. Every type declaration creates a new, distinct type: values of two different types cannot be mixed in an expression or assigned to each other without an explicit conversion, even if their ranges are identical.

Definition— Subtype

A subtype is an existing type with an added constraint, such as a narrower range. Values of a subtype and of its type mix freely, because they are the same type; the constraint is checked when a value is assigned to an object of the subtype or passed as a parameter.

Here are the scalar types you can declare, each with a typical example:

KindDeclarationValues
Signed integertype Floor is range -2 .. 40;whole numbers in the range; overflow raises an exception
Modular integertype Byte is mod 256;0 .. 255, with wrap-around arithmetic
Enumerationtype Signal is (Red, Amber, Green);the listed names, in order
Floating pointtype Ratio is digits 6;real numbers with at least 6 significant decimal digits
Ordinary fixed pointtype Volts is delta 0.001 range 0.0 .. 5.0;real numbers with a fixed absolute precision, held as scaled integers
Decimal fixed pointtype Money is delta 0.01 digits 12;exact decimal amounts, for money

Note

Fixed-point types store a value as a whole number of tiny steps, which makes them fast and predictable on processors without floating-point hardware. For an ordinary fixed-point type the step, called the small, is by default a power of two no larger than the delta: for Volts it is 1/1024, so 1.234 is stored as 1263/1024 and printed by GNAT 14 as 1.233. When the step must be exactly 0.001, say so with for Volts'Small use 0.001;, or use a decimal fixed-point type, whose step is always the decimal delta.

The language predefines a few: Integer (on GNAT a 32-bit type), Float, Boolean (an enumeration of False and True), Character (an enumeration too) and the subtypes Natural (0 .. Integer'Last) and Positive (1 .. Integer'Last). Experienced Ada programmers use Integer and Float sparingly, for genuinely generic counting and arithmetic. For anything with a meaning (an altitude, a channel number, a percentage) they declare a type.

A derived type copies an existing type's values and operations but is a new type: type Metres is new Float; and type Seconds is new Float; are both floating point, and you cannot add one to the other. Converting between related numeric types is written like a function call, Float (Distance), and is checked: converting 41 to Floor raises an exception.

A subtype gives a name to a constraint you use often:

ada
subtype Upper_Floor is Floor range 1 .. Floor'Last;
subtype Weekday     is Day   range Mon .. Fri;
subtype Percentage  is Integer range 0 .. 100;

Choosing between them is the main design decision. Use a new type when values mean something different and mixing them is a bug (floors and passengers). Use a subtype when values are the same kind of thing but some places only accept part of the range (any floor, versus an upper floor).

Attributes

Every scalar type comes with attributes, written Type'Name. The ones you will use daily:

AttributeMeaningDay example, with type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun)
'First, 'Lastsmallest and largest valueDay'First = Mon
'Rangethe range 'First .. 'Lastfor D in Day'Range loop
'Succ, 'Prednext and previous valueDay'Succ (Mon) = Tue
'Pos, 'Valposition number and backDay'Pos (Wed) = 2, Day'Val (2) = Wed
'Image, 'Valueto text and from textDay'Image (Sat) = "SAT", Day'Value ("sat") = Sat
'Min, 'Maxthe smaller or larger of two valuesInteger'Max (3, 9) = 9

Attributes keep code correct when declarations change. A loop written for F in Floor'Range stays right if the building gets a third basement; a loop written for F in -2 .. 40 silently does not.

Worked examplesH

Ranges and enumerations at work

A lift that cannot leave the building

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   type Floor is range -2 .. 40;               -- two basement levels
   type Passenger_Count is range 0 .. 12;      -- the lift's legal limit

   subtype Upper_Floor is Floor range 1 .. Floor'Last;

   Current : Floor := 0;
   Aboard  : Passenger_Count := 0;
   Target  : Upper_Floor := 5;
begin
   Put_Line ("Floors " & Floor'First'Image & " to" & Floor'Last'Image);

   Aboard := Aboard + 3;
   while Current < Target loop
      Current := Current + 1;
   end loop;
   Put_Line ("At floor" & Current'Image & " with" & Aboard'Image & " aboard");

   Current := Floor'Last;
   Current := Current + 1;                     -- one floor too many
   Put_Line ("This line is never reached");
exception
   when Constraint_Error =>
      Put_Line ("Constraint_Error: there is no floor above" & Floor'Last'Image);
end Main;

It prints:

text
Floors -2 to 40
At floor 5 with 3 aboard
Constraint_Error: there is no floor above 40

Notice three things. Current < Target compares a Floor with an Upper_Floor without complaint, because a subtype is the same type. The assignment Current := Current + 1 when Current is 40 raises Constraint_Error, Ada's exception for a value outside its range, and the exception part at the end of Main catches it (Lesson 3 covers exceptions properly). And GNAT noticed the problem before the program ever ran, printing at compile time:

text
main.adb:23:23: warning: value not in range of type "Floor" defined at line 5 [enabled by default]
main.adb:23:23: warning: Constraint_Error will be raised at run time [enabled by default]

Now try to mix the two types. Adding Aboard to Current does not compile:

text
main.adb:7:23: error: invalid operand types for operator "+"
main.adb:7:23: error: left operand has type "Floor" defined at line 2
main.adb:7:23: error: right operand has type "Passenger_Count" defined at line 3

This is the bug from the motivation, caught by the compiler. If you really mean to combine them you must write a conversion, and a reviewer will ask why.

Enumerations and case

Enumeration types name a fixed set of possibilities. Combined with the case statement, they give one of Ada's most useful guarantees: the compiler checks that every value is handled.

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
   subtype Weekday is Day range Mon .. Fri;

   Market_Day : constant Day := Day'Value ("thu");   -- text to value
   Hours      : Natural := 0;                         -- Natural is 0 .. Integer'Last
begin
   for D in Day loop
      case D is
         when Mon .. Thu => Hours := Hours + 8;
         when Fri        => Hours := Hours + 6;
         when Sat | Sun  => null;                     -- nothing to do
      end case;
   end loop;
   Put_Line ("Hours in a week:" & Hours'Image);

   Put_Line ("Market day is " & Market_Day'Image
             & ", day number" & Day'Pos (Market_Day)'Image
             & ", followed by " & Day'Succ (Market_Day)'Image);

   for D in reverse Weekday loop
      Put (D'Image & " ");
   end loop;
   New_Line;

   if Market_Day in Weekday then
      Put_Line ("The market is on a weekday.");
   end if;
   if Day'Last not in Weekday then
      Put_Line (Day'Last'Image & " is a day of rest.");
   end if;
end Main;

It prints:

text
Hours in a week: 38
Market day is THU, day number 3, followed by FRI
FRI THU WED TUE MON
The market is on a weekday.
SUN is a day of rest.

The case alternatives can be single values, ranges (Mon .. Thu) or choices joined by |. If you delete the line for Fri, the program no longer compiles, because Fri is not covered. When you later add a value to an enumeration, every case that forgot it becomes a compile error pointing at exactly the code to update. That is why experienced Ada programmers avoid when others => on enumerations: it would silence those errors. null; is Ada's explicit empty statement; an empty branch must say so.

Positions start at 0, so Day'Pos (Thu) is 3. 'Value accepts any capitalisation and raises Constraint_Error for text that is not a value of the type, which makes it a simple, safe parser. 'Image of an enumeration value gives the name in upper case. Membership tests, X in Weekday and X not in Weekday, work with any subtype or range, and since Ada 2012 also with lists of choices, as in if D in Sat | Sun then.

ComputationC

Decisions and loops

Ada's control flow will look familiar, with every construct closed by its own end:

ada
if Temperature > 30 then
   Open_Vents;
elsif Temperature < 10 then
   Start_Heater;
else
   null;
end if;

Conditions must be Boolean; there is no truthiness of numbers or pointers. and, or, xor and not evaluate both operands, while and then and or else stop early: if Count > 0 and then Total / Count > 10 never divides by zero. Mixing and and or without parentheses is a syntax error, so precedence questions cannot arise.

There is one loop construct with three headers: none (loop forever, leaving with exit), while and for. This program uses all three:

ada
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;

procedure Main is
   N     : Positive := 27;      -- Positive is 1 .. Integer'Last
   Steps : Natural  := 0;
   Peak  : Positive := N;
begin
   --  The Collatz rule: halve an even number, triple an odd one and add 1.
   while N /= 1 loop
      if N mod 2 = 0 then
         N := N / 2;
      else
         N := 3 * N + 1;
      end if;
      Steps := Steps + 1;
      Peak  := Positive'Max (Peak, N);
   end loop;
   Put_Line ("27 reaches 1 after" & Steps'Image & " steps, peaking at" & Peak'Image);

   --  A named loop lets an inner exit leave both loops at once.
   Search :
   for A in 1 .. 20 loop
      for B in A .. 20 loop
         if A * A + B * B = 13 * 13 then
            Put_Line ("13 squared is" & Integer'Image (A * A) & " +" & Integer'Image (B * B));
            exit Search;
         end if;
      end loop;
   end loop Search;

   --  A bare loop with exit when: the first power of 2 above 1000.
   declare
      Power : Positive := 1;
   begin
      loop
         Power := Power * 2;
         exit when Power > 1_000;
      end loop;
      Put_Line ("First power of 2 above 1000:" & Power'Image);
   end;
end Main;

It prints:

text
27 reaches 1 after 111 steps, peaking at 9232
13 squared is 25 + 144
First power of 2 above 1000: 1024

Points to notice:

  • /= means "not equal".
  • A for loop's variable is a constant inside the loop; assigning to it is a compile error. The range is evaluated once, before the first iteration. reverse counts down, but the range is still written low to high: for I in reverse 1 .. 10.
  • exit when Condition; leaves the innermost loop; exit Search; names the loop to leave. Naming a loop also documents it, and the name must be repeated after end loop.
  • A declare block (declare … begin … end;) introduces variables exactly where they are needed, with a scope that ends at its end.
  • Underscores may separate digits in a number, 1_000, as commas or spaces do in writing.

Arithmetic, honestly

Integer arithmetic is checked: an overflow raises Constraint_Error rather than wrapping silently, as it would in C or Java. When you want wrap-around, for checksums, hashes or hardware registers, you declare a modular type. For printing real numbers readably, Ada.Float_Text_IO.Put takes the number of digits before the point (Fore), after it (Aft) and in the exponent (Exp, 0 for none).

ada
pragma Ada_2022;
with Ada.Text_IO;       use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;

procedure Main is
   type Byte is mod 256;                 -- arithmetic wraps around
   B : Byte := 250;
   Big : Integer := Integer'Last;
   Price : constant Float := 19.99;
begin
   Put_Line ("   7 / 2 =" & Integer'Image (7 / 2)
             & "     (-7) / 2 =" & Integer'Image ((-7) / 2));
   Put_Line ("(-7) rem 2 =" & Integer'Image ((-7) rem 2)
             & "  (-7) mod 2 =" & Integer'Image ((-7) mod 2));
   Put_Line ("2 ** 10 =" & Integer'Image (2 ** 10));

   B := B + 10;
   Put_Line ("250 + 10 as a Byte:" & B'Image);

   Put ("Three items cost ");
   Put (3.0 * Price, Fore => 1, Aft => 2, Exp => 0);
   New_Line;

   Big := Big + 1;
   Put_Line ("unreachable" & Big'Image);
exception
   when Constraint_Error =>
      Put_Line ("Integer'Last + 1 raised Constraint_Error");
end Main;

It prints:

text
   7 / 2 = 3     (-7) / 2 =-3
(-7) rem 2 =-1  (-7) mod 2 = 1
2 ** 10 = 1024
250 + 10 as a Byte: 4
Three items cost 59.97
Integer'Last + 1 raised Constraint_Error

Integer / truncates toward zero, so (-7) / 2 is -3. Ada has two remainder operators. rem takes the sign of the left operand and pairs with /: (-7) = 2 × (-3) + (-1). mod takes the sign of the right operand, so (-7) mod 2 is 1, which is what you want for "is this number odd?" or for wrapping an index around a circle. ** raises to a natural-number power.

Common misconceptionsH

Common misunderstandings

Misconception

"-7 mod 2 is (-7) mod 2." In Ada, unary minus binds less tightly than mod, rem, * and /, so -7 mod 2 means -(7 mod 2), which is -1. GNAT 14 warns: unary minus expression should be parenthesized here. Write (-7) mod 2.

Misconception

"A subtype is a new type." subtype Percentage is Integer range 0 .. 100; is still Integer, so it mixes freely with other integers and only its range is checked. If you want the compiler to stop percentages being added to temperatures, declare type Percentage is range 0 .. 100;.

Misconception

"Integers wrap around when they overflow." Signed integer types never wrap in Ada: overflow raises Constraint_Error. Only modular types wrap, and you declare those on purpose.

Misconception

"when others makes a case statement safer." On an enumeration it makes it less safe: when a new value is added later, others quietly handles it instead of the compiler pointing at every case that needs a decision. Use others for wide types such as Integer or Character, where listing every value is impossible.

Exercises

Exercises

All outputs below were checked by compiling and running the code with GNAT 14.

1. Strong types and control flow

Warm-upHuman

A program handles heart rates (beats per minute) and ages (years), both whole numbers from 0 to 250. Which declarations make the compiler reject Rate + Age?

Choose one

2. Strong types and control flow

CoreComputational

What does Put_Line (Integer'Image ((-7) mod 3) & Integer'Image ((-7) rem 3)); print?

3. Strong types and control flow

CoreComputational

What value does the Ada expression -7 mod 2 have (written exactly like that, without parentheses)?

4. Strong types and control flow

Warm-upComputational

With type Day is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);, what does Put_Line (Day'Image (Day'Pred (Sun))); print?

5. Strong types and control flow

Warm-upComputational

With the same Day type, what is Day'Pos (Fri)?

6. Strong types and control flow

CoreComputational

In the Collatz program, N starts at 6 instead of 27. How many steps does it count before N reaches 1?

7. Strong types and control flow

CoreHuman

Given type Byte is mod 256; and type Level is range 0 .. 255;, with B : Byte := 255; and L : Level := 255;, what happens when the program runs B := B + 1; and then L := L + 1;?

Choose one

8. Strong types and control flow

StretchComputational

What does for I in reverse 3 .. 1 loop Put (I'Image); end loop; print?

Choose one

Further reading and resources