[your code here]

H. S. Teoh hsteoh at quickfur.ath.cx
Sat Feb 11 07:55:54 PST 2012


On Sat, Feb 11, 2012 at 10:47:01AM -0500, bearophile wrote:
> H. S. Teoh:
> 
> > > bool isKaprekar(in long n) pure nothrow
> > > in {
> > >     assert(n > 0, "isKaprekar(n): n must be > 0");
> > >     assert(n <= uint.max, "isKaprekar(n): n must be <= uint.max");
> > > } body {
> > [...]
> > 
> > Shouldn't you just use "in ulong n" as parameter instead of long with a
> > contract?
> 
> In this case the answer is probably positive.
> 
> But in general it's better to accept a signed number and then refuse
> the negative values in the pre-condition, otherwise if you give by
> mistake a negative number to the function it's not caught.
> 
> Such work-arounds are less needed in saner languages, where the ranges
> of integral values are verified, at compile time where possible, and
> at run-time otherwise. Unwanted wrap-arounds and undetected overflows
> in integral values are so '70 :-)
[...]

Hmph. I was under the impression that D was clever enough to be able to
detect overflow problems when dealing with signed->unsigned conversion.

The bad thing about taking signed long as parameter and then restrict it
to 0..uint.max means that you're unnecessarily constraining the domain
of the function.


T

-- 
Being able to learn is a great learning; being able to unlearn is a
greater learning.


More information about the Digitalmars-d mailing list