T'Base refers to the "base range" of the type, which defines the range in which intermediate calculations are performed.
Base for Integer TypesEdit
The standard states that the range of T'Base:
- includes the value 0
- is symmetric about zero, with possibly an extra negative value
- includes all of the values in the subtype T
So for example, if T is:
then the compiler will choose a hardware supported type that includes this range, in this case probably an eight bit type (on a two's complement machine)
This definition is not to be taken literally, as by Ada semantics, T and T'Base would be incompatible. In effect, the declaration of T would then be
Note that built-in operators go through the base type, and T's "+" op for example is implicitly declared as:
There are no constraint checks on T'Base, so for example:
then in the first assignment to O1, there is a constraint check to ensure that the result of 1 + 2 is in the range of T, but in the second assignment to O2, there is no check.
T'Base is useful for generics, when you need to be able to recover the base range of the type, in order to declare an object with value 0; for example, if this is an accumulator.
It is helpful to know something about the base range of the type, so that you have a guarantee that you don't get any overflow during intermediate calculations. For example, given type T above then:
This is a problem, since if the sum of O1 and O2 is large (that is, greater than T'Base'Last), then you'll get overflow. Knowing that you're going to be adding two values together means you should declare the type this way:
That way you know that (sub)type T's range is 1 .. 42, but you also have a guarantee that T'Base'Last >= 84, and hence the sum of two values of type T cannot overflow.
Note that a declaration of the form:
actually declares a subtype, named T, of some anonymous base type. We can refer to the range of this base type as T'Base.
Base for Enumeration TypesEdit
An enumeration type is its own base type, so given this type:
then the range of ET is the same as the range of ET'Base. If you need some extra literals in your "base" type, then you have to declare them manually, not unlike what we did above:
Now you can say ET'Succ (ET'Last) and you'll get a meaningful answer. This is necessary when you do something like:
declareE : ET'Base := ET'First;
whileE <= ET'Last
loop... -- do something E := ET'Succ (E);
Also when you derive from ET_Base with a range constraint, the base of the derived type will include all values of the base type:
rangeA .. C; Correct:
constantBoolean := New_ET'Base'First = ET_Base_First;
Note that here ET_BASE_First is of type New_ET.
If you declare:
then Sub_Enum'Base'Last is Enum3.