Ada Programming/Attributes/'Valid
Description
editObjects may become invalid via import, unchecked conversions, overlays, etc.
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.
Example
edit-- Declare a discrete type and explicitly set the position numberstype
My_Enumis
(Value1, Value2, Value3);for
My_Enumuse
(Value1 => 2, Value2 => 4, Value3 => 6 ); Result : Natural; Enum_Var, Other_Var: My_Enum; Sneaky_Back_Door : Integer;for
Enum_Var'Addressuse
Sneaky_Back_Door'Address; ...if
not
Result'Validthen
-- Result is out-of-range, it has a negative value Result := Natural'First;end
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 ...if
not
Enum_Var'Validthen
-- this is not reading -- Enum_Var contains a bad value Enum_Var := My_Enum'First;end
if
;
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.
See also
editWikibook
editAda Reference Manual
editAda Quality and Style Guide
edit- 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.