Ada Programming/Attributes/'Valid


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

Description

edit

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

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

edit

Wikibook

edit

Ada Reference Manual

edit

Ada Quality and Style Guide

edit

Ada Rationale

edit