< Ada Programming < Attributes 
 
 
      
Ada. Time-tested, safe and secure.
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.)
functionS'Val (Arg: universal_integer)returnS'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.typeMy_Enumis(Enum1, Enum2, Enum3); -- Declare a discrete type and explicitly set the internal representation. -- Note that the position numbers are still 0 .. 2.typeMy_Other_Enumis(Value1, Value2, Value3);forMy_Other_Enumuse(Value1 => 2, Value2 => 4, Value3 => 6);pragmaAssert (My_Enum'Val(0) = Enum1); -- OKpragmaAssert (My_Enum'Val(1) = Enum2); -- OKpragmaAssert (My_Enum'Val(2) = Enum3); -- OKpragmaAssert (My_Other_Enum'Val(0) = Value1); -- OKpragmaAssert (My_Other_Enum'Val(1) = Value2); -- OKpragmaAssert (My_Other_Enum'Val(2) = Value3); -- OKpragmaAssert (My_Enum'Val(3) = Enum3); -- WrongpragmaAssert (My_Other_Enum'Val(2) = Value1); -- WrongpragmaAssert (My_Other_Enum'Val(4) = Value2); -- WrongpragmaAssert (My_Other_Enum'Val(6) = Value3); -- Wrong
Other example:
typeColoris(RED, BLUE, WHITE); OBJECT : Color := WHITE;beginPut (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 Reference Manual
    This article is issued from Wikibooks. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.