Ada Programming/Attributes/'Val

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Ada. Time-tested, safe and secure.
Ada. Time-tested, safe and secure.

Description[edit | edit source]

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[edit | edit source]

-- 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

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[edit | edit source]

The inverse of the 'Val attribute is 'Pos.

Wikibook[edit | edit source]

Ada Reference Manual[edit | edit source]