The Valid attribute can be used with an object of any scalar type (that is, numeric or enumeration types) to know whether its value is valid (e.g. not out-of-range, etc.). The result is always True or False; neither Constraint_Error nor any other exception are ever raised.
It is important that the evaluation of the attribute does not count as reading the object, whereas reading an invalid object makes the program erroneous.
-- Declare a discrete type and explicitly set the position numbers
is(Value1, Value2, Value3);
use(Value1 => 2, Value2 => 4, Value3 => 6 ); Result : Natural; Enum_Var, Other_Var: My_Enum; Sneaky_Back_Door : Integer;
then-- Result is out-of-range, it has a negative value Result := Natural'First;
if; ... -- Assign a bad integer value to the enumerated type variable. Sneaky_Back_Door := 1; Other_Var := Enum_Var; -- reading Enum_Var makes the program erroneous ...
then-- this is not reading -- Enum_Var contains a bad value Enum_Var := My_Enum'First;
Note that in the erroneous assignment statement above, no range check is performed (hence no exception will be raised) since both variables are of the same subtype.
Ada Reference ManualEdit
Ada Quality and Style GuideEdit
- 5.9.1 Unchecked Conversion — Consider using the 'Valid attribute to check the validity of scalar data.
- 5.9.7 Direct_IO and Sequential_IO — Use the 'Valid attribute to check the validity of scalar values obtained through Ada.Direct_IO and Ada.Sequential_IO.
- 6.3.3 The Abort Statement — In the presence of the abort statement, consider using the 'Valid attribute to check the validity of scalar data.