Section 8.4 - Passing String Between Subprograms

Strings can be passed between subprograms just like any other variable type. Procedures and functions can have a type String as an in (or in out) variable, and those parameters will be set when the subprogram is called. In addition, functions can return variables of type String, just like any other type.

Beginning Ada developers often make an unwarranted assumption when writing subprograms that accept Strings - they assume that String indexes always begin with one. Not true. String indexes do not have to start at one - that's just the smallest possible starting index. In particular, if you pass in a string slice as an input parameter to a subprogram, the receiving subprogram will receive the slice's index values. This helps to keep String efficient, but it can be surprising.

The smallest index value of a String named A is written as A'First. Similarly, the largest index value is A'Last, and the string's length is A'Length.

Here's a simple rule of thumb: whenever you write a subprogram that accepts a String variable as an in parameter, always use 'First, 'Last, and 'Length - never assume that the String index begins with one. If you try to reference an out-of-range index, Ada will raise an exception - but it's better to not make the mistake in the first place.

Here is an example, which will hopefully make this clearer:

  with Text_IO; use Text_IO;
  procedure String2 is

    procedure Print_Reverse( S : String ) is
      for I in reverse S'First .. S'Last loop
      end loop;
    end Print_Reverse;
    Demo : String := "A test";
  end String2;


When Print_Reverse is called, which is true?

  1. S="test", S'First=3, S'Length=4
  2. S="test", S'First=1, S'Length=4

You may also:

PREVIOUS Go back to the previous section

NEXT     Skip to the next section

OUTLINE  Go up to lesson 8 outline

David A. Wheeler (

The master copy of this file is at "".