Why is size_t unsigned?

Marco Leise Marco.Leise at gmx.de
Mon Jul 22 10:39:29 PDT 2013


Am Mon, 22 Jul 2013 05:47:34 +0200
schrieb "JS" <js.mdnq at gmail.com>:

> Doing simple stuff like
> 
> for(int i = 0; i < s.length - 1; i++) fails catastrophically if s 
> is empty. To make right one has to reduce performance by writing 
> extra checks.

And my opinion on the matter is that it is catastrophic style
to subtract 1 from a length that's possibly 0. Please write:

if (s.length) foreach (i; 0 .. s.length - 1)

> There seems to be no real good reason why size_t is unsigned... 
> Surely one doesn't require too many strings larger than 2^63 bits 
> on an x64 os...

So the size_t should be signed on 64-bit systems and unsigned
on 32-bit systems? And please note that all length properties
are unsigned, strings, other arrays, range structures, tuples
and bit arrays have a ulong length, because they can
theoretically hold more bits than 2^32 on 32-bit systems.

> I running into a lot of trouble because of the way D deals with 
> implicit casting of between signed and unsigned.

That's a good point. There are languages that disallow this
implicit conversion. I'd also like size_t to be a type of its
own, so you cannot mess up by assigning a size_t to a uint
while developing on 32-bit.

> please don't tell me to use foreach... isn't not a panacea.

Yes, please.

-- 
Marco



More information about the Digitalmars-d-learn mailing list