当我使用以 127 结尾的范围定义自己的类型时,编译器不会进行上限检查,这允许变量回绕并在其定义的限制以下变为负数。如果我将范围定义为 126,则会引发正确的异常。我在下面包含了这些程序及其输出。
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure GoodType is
type GOOD_TYPE is range -1..126;
package GOOD_TYPE_IO is new Ada.Text_IO.Integer_IO(GOOD_TYPE);
use GOOD_TYPE_IO;
On_Both1 : GOOD_TYPE := 120;
Index : INTEGER := 0;
begin
for Index in 120..130 loop
On_Both1 := On_Both1 + 1;
Put(Index);
Put(": ");
Put(On_Both1);
New_line;
end loop;
end GoodType;
输出:
gnatmake -f goodtype.adb && ./goodtype
120: 121
121: 122
122: 123
123: 124
124: 125
125: 126
raised CONSTRAINT_ERROR : goodtype.adb:16 range check failed
.
with Ada.Text_IO, Ada.Integer_Text_IO;
use Ada.Text_IO, Ada.Integer_Text_IO;
procedure BadType is
type BAD_TYPE is range -1..127;
package BAD_TYPE_IO is new Ada.Text_IO.Integer_IO(BAD_TYPE);
use BAD_TYPE_IO;
On_Both1 : BAD_TYPE := 120;
Index : INTEGER := 0;
begin
for Index in 120..130 loop
On_Both1 := On_Both1 + 1;
Put(Index);
Put(": ");
Put(On_Both1);
New_line;
end loop;
end BadType;
输出:
gnatmake -f badtype.adb && ./badtype
120: 121
121: 122
122: 123
123: 124
124: 125
125: 126
126: 127
127: -128
128: -127
129: -126
130: -125