Ada 95 Quality and Style Guide Chapter 7

Chapter 7: Portability - TOC - 7.2 NUMERIC TYPES AND EXPRESSIONS

7.2.6 Subexpression Evaluation

guideline

  • Anticipate the range of values of subexpressions to avoid exceeding the underlying range of their base type. Use derived types, subtypes, factoring, and range constraints on numeric types (see Guidelines 3.4.1, 5.3.1, and 5.5.3).
  • example

    This example is adapted from the Rationale (1995, 3.3):

    with Ada.Text_IO;
    with Ada.Integer_Text_IO;
    procedure Demo_Overflow is
    -- assume the predefined type Integer has a 16-bit range
       X : Integer := 24_000;
       Y : Integer;
    begin  -- Demo_Overflow
       y := (3 * X) / 4;  -- raises Constraint_Error if the machine registers used are 16-bit
      -- mathematically correct intermediate result if 32-bit registers
       Ada.Text_IO.Put ("(");
       Ada.Integer_Text_IO.Put (X);
       Ada.Text_IO.Put (" * 3 ) / 4 = ");
       Ada.Integer_Text_IO.Put (Y);
    exception
       when Constraint_Error =>
          Ada.Text_IO.Put_Line ("3 * X too big for register!");
    end Demo_Overflow;
    

    rationale

    The Ada language does not require that an implementation perform range checks on subexpressions within an expression. Ada does require that overflow checks be performed. Thus, depending on the order of evaluation and the size of the registers, a subexpression will either overflow or produce the mathematically correct result. In the event of an overflow, you will get the exception Constraint_Error. Even if the implementation on your program's current target does not result in an overflow on a subexpression evaluation, your program might be ported to an implementation that does.


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