Ada Programming/Attributes/'Val

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Ada Lovelace 1838.jpg

Contents


[edit] Description

X'Val(Y) is an Ada attribute where X is any discrete type and Y is an integer. This attribute represents the value of type X that has the same position number as Y. If no value of type X has a position number of Y, a CONSTRAINT_ERROR exception is raised.

Note that representation clauses do not effect position numbering. Whatever underlying value the enumerated value has, the position number will remain the same.

[edit] Example

-- Declare a discrete type and assume we know what
-- position numbers the compiler will assign the values 
type My_Enum is (Enum1, Enum2, Enum3);

-- Declare a discrete type and explicitly set the position numbers
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

[edit] See also

[edit] Wikibook

[edit] Ada Reference Manual