411 REFERENCE · Wikibooks
Ada Programming/Attributes/'Valid
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Attributes 'Valid
__TOC__
Description
Objects 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
Declare a discrete type and explicitly set the position numbers
type My_Enum is (Value1, Value2, Value3);
for My_Enum use (Value1 => 2, Value2 => 4, Value3 => 6 );
Result : Natural;
Enum_Var, Other_Var: My_Enum;
Sneaky_Back_Door : Integer;
for Enum_Var'Address use Sneaky_Back_Door'Address;
...
if not Result'Valid then
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'Valid then 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
Wikibook
Ada Programming
Ada Programming/Attributes
Ada Reference Manual
13 9 2 The Valid Attribute
Ada Quality and Style Guide
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.
Ada Rationale
3 h 1 1 The Valid Attribute
Valid