Ada Programming/Attributes/'Val
Description
editThe '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
edit-- Declare a discrete type; the compiler will assign the internal representation as 0 .. 2 -- identical to the position numbers.type
My_Enumis
(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_Enumis
(Value1, Value2, Value3);for
My_Other_Enumuse
(Value1 => 2, Value2 => 4, Value3 => 6);pragma
Assert (My_Enum'Val(0) = Enum1); -- OKpragma
Assert (My_Enum'Val(1) = Enum2); -- OKpragma
Assert (My_Enum'Val(2) = Enum3); -- OKpragma
Assert (My_Other_Enum'Val(0) = Value1); -- OKpragma
Assert (My_Other_Enum'Val(1) = Value2); -- OKpragma
Assert (My_Other_Enum'Val(2) = Value3); -- OKpragma
Assert (My_Enum'Val(3) = Enum3); -- Wrongpragma
Assert (My_Other_Enum'Val(2) = Value1); -- Wrongpragma
Assert (My_Other_Enum'Val(4) = Value2); -- Wrongpragma
Assert (My_Other_Enum'Val(6) = Value3); -- Wrong
Other example:
type
Coloris
(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
editThe inverse of the 'Val attribute is 'Pos.