dzrubtdp
dzrubtdp

Reputation: 1

Is the use of a type where its range-restricted subtype is expected considered correct in Ada?

According to slide 28 of https://github.com/AdaCoreU/Courses/blob/master/lectures/03_Programming_in_the_Large/02_Type_Safety/slides/Strong_Typing.ppt?raw=true the below code is correct, because "T is a subtype of Integer. Therefore, V1 and V2 are of the same type"

procedure weirdada is
  subtype T is Integer range 1 .. Integer'Last;
  V1 : Integer := 0;
  V2 : T := V1;
begin
  null;
end;

But what is the purpose of a range declaration if I am allowed violate it? My thinking seems correct, since there is a warning at compiletime, and an exception at runtime.

$ ./gnat-gpl-2014-x86-linux-bin/bin/gnatmake weirdada.adb
gcc -c weirdada.adb
weirdada.adb:4:19: warning: value not in range of type "T" defined at line 2
weirdada.adb:4:19: warning: "Constraint_Error" will be raised at run time
gnatbind -x weirdada.ali
gnatlink weirdada.ali

$ ./weirdada
raised CONSTRAINT_ERROR : weirdada.adb:4 range check failed

Is the slide incorrect, or am I misunderstanding something?

Upvotes: 0

Views: 205

Answers (1)

Jacob Sparre Andersen
Jacob Sparre Andersen

Reputation: 6601

Ada distinguishes between types and subtypes. Types are separate spaces of values. Subtypes are compatible subsets of a given type.

As it isn't generally possible to make a compile-time check of a conversion between different subtypes of a type (technically both T and Integer are subtypes), all such conversions are considered legal at compile-time, but may of course be fail at run-time, if the actual value doesn't fit in the target subtype.

So yes, you may have missed the difference between types and subtypes.

Upvotes: 3

Related Questions