Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Types and Control Flow

Arrays and Strings in Ada: Bounds, Slices and Attributes

Master Ada arrays: any discrete index range, constrained and unconstrained types, slices, aggregates, the attributes First, Last, Range and Length, and why String is just an array.

An Ada array can use any discrete type as its index and any lower bound you like. The bounds are part of the type or object, they are checked on every access, and you can always ask an array for its own 'First, 'Last and 'Length. Strings are simply arrays of characters, so everything here applies to them as well.

Ada code is read-only on this site; C stand-ins reproduce the checks.

Constrained arrays

ADA
type Scores is array (1 .. 5) of Integer;
type Hours  is array (Day) of Natural;        --  indexed by an enumeration

S : Scores := (10, 20, 30, 40, 50);
H : Hours  := (Mon .. Fri => 8, others => 0);

The right-hand sides are aggregates: lists of values in parentheses. You can use named association (2 => 7), ranges (1 .. 3 => 0), choice lists (1 | 5 => 9) and others for the rest. Positional and named parts can be mixed as long as others comes last.

Access uses parentheses, not brackets: S (3). An index outside 1 .. 5 raises Constraint_Error.

Attributes you will use constantly

ADA
S'First     --  1
S'Last      --  5
S'Length    --  5
S'Range     --  1 .. 5

S'Range is the idiom for looping over an array without hard-coding bounds:

ADA
Total : Integer := 0;
for I in S'Range loop
   Total := Total + S (I);
end loop;

In Ada 2012 you can also write for X of S loop Total := Total + X; end loop;, which iterates over the elements directly.

Unconstrained arrays

An unconstrained array type leaves the bounds open until you create an object:

ADA
type Int_Vector is array (Positive range <>) of Integer;

V1 : Int_Vector (1 .. 4) := (4, 3, 2, 1);
V2 : Int_Vector := (7, 8, 9);          --  bounds come from the aggregate: 1 .. 3

This lets one function work for arrays of any length, which is how Ada avoids the C habit of passing a pointer and a count:

ADA
function Sum (V : Int_Vector) return Integer is
   Result : Integer := 0;
begin
   for I in V'Range loop
      Result := Result + V (I);
   end loop;
   return Result;
end Sum;

The bounds travel with the array, so Sum is correct for 1 .. 4 and for 10 .. 12.

Slices and concatenation

A slice is a contiguous part of an array:

ADA
V1 (2 .. 3)          --  the elements at index 2 and 3
V1 (1 .. 2) := V1 (3 .. 4);   --  slice assignment

The & operator concatenates arrays and strings. Arrays can be compared with = element by element, and for discrete elements you can use <, which gives lexicographic order.

Multidimensional arrays

ADA
type Grid is array (1 .. 3, 1 .. 3) of Character;
G : Grid := (others => (others => '.'));
G (2, 2) := 'X';

Each dimension has its own bounds, and attributes take a dimension number: G'Length (1), G'Range (2).

Strings

String is predefined as array (Positive range <>) of Character. A literal such as "Hello" has bounds 1 .. 5. Because strings are arrays:

  • Their length is fixed once created. Assigning a string of a different length to a String (1 .. 5) raises Constraint_Error.
  • Slices work: Name (1 .. 3).
  • & concatenates: "Hi " & Name.
  • For variable-length text, use Ada.Strings.Unbounded (a growing string type) or Ada.Strings.Bounded.
ADA
Line : String (1 .. 80);
Last : Natural;
...
Get_Line (Line, Last);
Put_Line (Line (1 .. Last));    --  only the part actually read

Stand-in: bounds travel with the array

C arrays do not know their length. This stand-in packages a pointer with a lower and upper bound so that Sum works on any range, checks every index, and prints a Constraint_Error message for a bad one, as Ada does.

C Stand-in: an array that carries its bounds

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A second stand-in shows slicing and the fixed length of Ada strings: copying a longer string into a shorter object is rejected instead of overflowing.

C Stand-in: slices and length-checked assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Using square brackets: Ada indexes with parentheses.
  • Assuming strings start at 0. A string's lower bound is usually 1, but a slice can have any bounds; always use 'First and 'Last.
  • Assigning strings of different lengths.
  • Forgetting that Get_Line returns the count in Last.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does V'Range give for V : Int_Vector (3 .. 7)?

    'Range is 'First .. 'Last, the actual bounds of the array.
  2. 2. What is an unconstrained array type used for?

    Leaving the index range open (range <>) lets one function accept arrays of any length.
  3. 3. What happens when you assign "Hello!" to Name : String (1 .. 5)?

    Lengths must match for array assignment; the mismatch is a run-time check failure (or a compile-time warning).
  4. 4. How do you write a slice of elements 2 to 4 of array A?

    A slice is the array name followed by a discrete range in parentheses.

Summary

  • Arrays can be indexed by any discrete type with any bounds; access uses parentheses and is checked.
  • Constrained arrays fix bounds in the type; unconstrained arrays fix them per object.
  • 'First, 'Last, 'Length and 'Range let code adapt to any bounds; slices and & combine arrays.
  • String is an array of Character; use Unbounded strings for variable length.

Next: Records and Aggregates