Why is size_t unsigned?

H. S. Teoh hsteoh at quickfur.ath.cx
Sun Jul 21 21:29:34 PDT 2013


On Mon, Jul 22, 2013 at 05:47:34AM +0200, JS wrote:
> 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.

I'm not sure if it's your intention, but your code above has an off-by-1
error (unless you were planning on iterating over one less element than
there are).


> There seems to be no real good reason why size_t is unsigned...
[...]

The reason is because it must span the range of CPU-addressable memory
addresses. Note that due to way virtual memory works, that may have
nothing to do with the actual size of your data (e.g. on Linux, it's
possible to allocate more memory than you actually have, as long as you
don't actually use it all -- the kernel simply maps the addresses in
your page tables into a single zeroed-out page, and marks it as
copy-on-write, so you can actually have an array bigger than available
memory as long as most of the elements are binary zeroes (though I don't
know if druntime currently actually supports such a thing)).


T

-- 
MASM = Mana Ada Sistem, Man!


More information about the Digitalmars-d-learn mailing list