A little puzzle

Simen Kjaeraas simen.kjaras at gmail.com
Mon Sep 19 15:09:45 PDT 2011


On Mon, 19 Sep 2011 23:20:47 +0200, bearophile <bearophileHUGS at lycos.com>  
wrote:

> A tiny puzzle I've shown on IRC. This is supposed to create an inverted  
> array of cards, but what does it print instead?
>
> import std.stdio, std.algorithm, std.range;
> void main() {
>     int[52] cards;
>     copy(iota(cards.length - 1, -1, -1), cards[]);
>     writeln(cards);
> }

Gawds, that's an ugly bug. For those who can't spot it,
typeof(cards.length) == uint, hence -1 is converted to a uint
(4_294_967_295, to be exact). iota then says 'that's fine, I'll just
return an empty range for you.'
Solution: knock some sense into integral promotion rules.
Workaround: cast(int)cards.length.

What was the rationale for having unsigned array lengths, again?

-- 
   Simen


More information about the Digitalmars-d-learn mailing list