Ada 95 Quality and Style Guide Chapter 5

Chapter 5: Programming Practices - TOC - 5.5 EXPRESSIONS

5.5.1 Range Values


  • Use 'First or 'Last instead of numeric literals to represent the first or last values of a range.
  • Use 'Range or the subtype name of the range instead of 'First .. 'Last.

  • example
    type Temperature      is range All_Time_Low .. All_Time_High;
    type Weather_Stations is range            1 ..  Max_Stations;
    Current_Temperature : Temperature := 60;
    Offset              : Temperature;
    for I in Weather_Stations loop
       Offset := Current_Temperature - Temperature'First;
    end loop;


    In the example above, it is better to use Weather_Stations in the for loop than to use Weather_Stations'First .. Weather_Stations'Last or 1 .. Max_Stations because it is clearer, less error-prone, and less dependent on the definition of the type Weather_Stations. Similarly, it is better to use Temperature'First in the offset calculation than to use All_Time_Low because the code will still be correct if the definition of the subtype Temperature is changed. This enhances program reliability.


    When you implicitly specify ranges and attributes like this, be careful that you use the correct subtype name. It is easy to refer to a very large range without realizing it. For example, given the declarations:

    type    Large_Range is new Integer;
    subtype Small_Range is Large_Range range 1 .. 10;
    type Large_Array is array (Large_Range) of Integer;
    type Small_Array is array (Small_Range) of Integer;

    then the first declaration below works fine, but the second one is probably an accident and raises an exception on most machines because it is requesting a huge array (indexed from the smallest integer to the largest one):

    Array_1 : Small_Array;
    Array_2 : Large_Array;

    < Previous Page Search Contents Index Next Page >
    1 2 3 4 5 6 7 8 9 10 11
    Appendix References Bibliography