Make size_t its own type
Quirin Schroll
qs.il.paperinik at gmail.com
Thu Jan 23 16:00:20 UTC 2025
The title says it: Make `size_t` be a type that’s distinguished
from all currently existing unsigned types.
The rationale for that is that conversions from and to `size_t`
fail and succeed depending on compile-target. On a 32-bit
machine, `size_t` is an alias of `uint` and on a 64-bit it’s an
alias of `ulong` ― I know it’s not defined that way, but it ends
up being that. That means `size_t` implicitly converts to `uint`
on 32-bit and `ulong` implicitly converts to `size_t` on 64-bit,
but flip the architectures and the conversions fail. This means
writing portable code is needlessly hard.
If `size_t` were its own type, the language could reject any
implicit conversion that would fail on any target supported by
the compiler / the language.
There are already unsigned and signed types and character types.
Speaking of x86 assembly, there is no difference between `uint`,
`int`, and `dchar`, i.e. they all use the same 32-bit registers;
that’s contrary to `float` which does have dedicated floating
point registers. Yet, most languages distinguish `uint`, `int`,
and `dchar`. They are conceptually different enough to warrant
being different types. IMO, that applies to `size_t` even more
because it isn’t even consistent across targets.
AFAIK, D only supports 32- and 64-bit targets. So `size_t` could
be initialized by a `uint` (and anything that implicitly converts
to `uint`), and implicitly converts to `ulong`.
What could be added is allowing the target-specific implicit
conversions (e.g. `size_t` to `uint` or `ulong` to `size_t`) if
the code is in under a `version` statement of which the compiler
knows it determines the width of `size_t`.
---
My experience comes from working on a C++ project where we still
have to support 32-bit Windows and had to support 32-bit Linux up
to last year. We have many warnings on and treat all of them as
errors across 5 compilers, including loss of precision on
implicit casts. D could make it easier for its users not to run
into these all the time.
More information about the dip.ideas
mailing list