411 REFERENCE · Wikibooks
Ada Programming/Attributes/'Val
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Attributes 'Val
__TOC__
Description
The 'Val attribute is defined for all discrete types. It is a function returning that value of the base type of S having the argument's position number; the prefix S must be a subtype name. (Any specific integer type is implicitly converted to universal_integer.)
function S'Val (Arg: universal_integer) return S'Base;
If no value of the type of S has the position number Arg, the Constraint_Error exception is raised.
Note that representation clauses do not affect position numbering. Whatever underlying value the enumerated value has, the position number will remain the same.
Example
Declare a discrete type; the compiler will assign the internal representation as 0 .. 2
identical to the position numbers.
type My_Enum is (Enum1, Enum2, Enum3);
Declare a discrete type and explicitly set the internal representation.
Note that the position numbers are still 0 .. 2.
type My_Other_Enum is (Value1, Value2, Value3);
for My_Other_Enum use (Value1 => 2, Value2 => 4, Value3 => 6);
Assert (My_Enum'Val(0) = Enum1); OK
Assert (My_Enum'Val(1) = Enum2); OK
Assert (My_Enum'Val(2) = Enum3); OK
Assert (My_Other_Enum'Val(0) = Value1); OK
Assert (My_Other_Enum'Val(1) = Value2); OK
Assert (My_Other_Enum'Val(2) = Value3); OK
Assert (My_Enum'Val(3) = Enum3); Wrong
Assert (My_Other_Enum'Val(2) = Value1); Wrong
Assert (My_Other_Enum'Val(4) = Value2); Wrong
Assert (My_Other_Enum'Val(6) = Value3); Wrong
Other example:
type Color is (RED, BLUE, WHITE);
OBJECT : Color := WHITE;
begin
Put (Color'Val (1)); give BLUE
The internal representation can only be queried via Unchecked_Conversion.
See also
The inverse of the 'Val attribute is 'Pos.
Wikibook
Ada Programming
Ada Programming/Attributes
Ada Programming/Attributes/'Pos
Ada Reference Manual
13 3 Operational and Representation Attributes
K Language-Defined Attributes
Val