From: Adam Beneschan <adam@irvine.com>
Subject: Re: Type of subtraction operator
Date: Thu, 28 May 2009 14:54:28 -0700 (PDT)
Date: 2009-05-28T14:54:28-07:00 [thread overview]
Message-ID: <82dc202a-e725-4056-9a5b-967b2a47c1df@p21g2000prn.googlegroups.com> (raw)
In-Reply-To: 8ae800c6-4307-4dc5-bf6b-d97101ae8521@x5g2000yqk.googlegroups.com
On May 28, 2:23 pm, Maciej Sobczak <see.my.homep...@gmail.com> wrote:
> According to 4.5.3/2, each numeric type has a subtraction operator
> with this specification:
>
> function "-"(Left, Right : T) return T
>
> This means that the type of difference is the same as the type of
> operands.
>
> Which means that if T is Natural, then I should expect
> CONSTRAINT_ERROR when the result of subtraction is less than 0.
> But it does not happen:
Natural is not a type. It's a subtype. The subtraction operator is
defined on the underlying type, Integer's type, rather than the
subtype. (Integer is also a subtype, rather than a type; see 3.5.4
(11).) The result of the function is then converted to the subtype
Integer, and no Constraint_Error occurs since -2 is within Integer's
range.
> with Ada.Text_IO;
> procedure Test is
>
> X : Natural := 5;
> Y : Natural := 7;
> Z : Integer := X - Y; -- here the result is not in Natural'Range
>
> begin
> Ada.Text_IO.Put_Line (Integer'Image (Z));
> end Test;
>
> The above happily prints -2.
> I thought initially that it is a subtype that is responsible for this,
> but defining My_Natural type as a completely new type (with
> appropriate type cast when Z is initialized) gives the same result.
My_Natural is not a type either. It's a subtype of some new integer
base type whose base range will include both negative and positive
numbers (symmetric about zero)---see 3.5.4(1), 3.5.4(9).
> I conclude that the effective type of difference (the return type of
> the "-" operator) is T'Base instead of T.
No, it's T. 4.5.3(1) refers to T as a type, not a subtype. Your
mistake, which is natural enough (hee hee hee), was in assuming that
My_Natural is a type. The "-" operator is defined on the base type of
which My_Natural is a subtype.
Yep, it's confusing. It took me some time to figure all this out too.
-- Adam
next prev parent reply other threads:[~2009-05-28 21:54 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2009-05-28 21:23 Type of subtraction operator Maciej Sobczak
2009-05-28 21:54 ` Adam Beneschan [this message]
2009-05-29 2:09 ` anon
2009-05-29 15:24 ` Adam Beneschan
2009-05-30 7:47 ` anon
replies disabled
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox