Ada Programming/Attributes/'Val
< Ada Programming < AttributesComputing » Computer Science » Computer Programming » Ada Programming

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); pragma Assert (My_Enum'Val(0) = Enum1); -- OK pragma Assert (My_Enum'Val(1) = Enum2); -- OK pragma Assert (My_Enum'Val(2) = Enum3); -- OK pragma Assert (My_Other_Enum'Val(0) = Value1); -- OK pragma Assert (My_Other_Enum'Val(1) = Value2); -- OK pragma Assert (My_Other_Enum'Val(2) = Value3); -- OK pragma Assert (My_Enum'Val(3) = Enum3); -- Wrong pragma Assert (My_Other_Enum'Val(2) = Value1); -- Wrong pragma Assert (My_Other_Enum'Val(4) = Value2); -- Wrong pragma Assert (My_Other_Enum'Val(6) = Value3); -- Wrong
The internal representation can only be queried via Unchecked_Conversion.
See also
The inverse of the 'Val attribute is 'Pos.
Wikibook
Ada Reference Manual
- 13.3 Operational and Representation Attributes (Annotated)
- Annex K Language-Defined Attributes (Annotated)
This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.