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 begin for I in reverse S'First .. S'Last loop Put(S(I)); end loop; end Print_Reverse; Demo : String := "A test"; begin Print_Reverse(Demo(3..Demo'Last)); end String2;
When Print_Reverse is called, which is true?
|Go back to the previous section||Skip to the next section||Go up to lesson 8 outline|
David A. Wheeler (firstname.lastname@example.org)
The master copy of this file is at
The master copy of this file is at "http://www.adahome.com/Tutorials/Lovelace/s8s4.htm".