跳轉到內容

Ada 程式設計/屬性/'Valid

來自 Wikibooks,開放的書籍,開放的世界

Ada. Time-tested, safe and secure.
Ada. 經久考驗,安全可靠。

物件可以透過 匯入未經檢查的轉換覆蓋 等方式變為無效。

Valid 屬性 可以與任何標量型別(即數字或列舉型別)的物件一起使用,以確定其值是否有效(例如,不在範圍之外等)。結果始終為 True 或 False;不會引發 Constraint_Error 或任何其他 異常

重要的是,屬性的計算不計入讀取物件,而讀取無效物件會使程式出現錯誤。

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

請注意,在上面的錯誤賦值語句中,由於兩個變數都是相同子型別的,因此沒有執行範圍檢查(因此不會引發異常)。

Ada 參考手冊

[編輯 | 編輯原始碼]

Ada 質量和風格指南

[編輯 | 編輯原始碼]

Ada 理念

[編輯 | 編輯原始碼]
華夏公益教科書