Why is size_t not a typedef

Jonathan Marler via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 7 13:13:08 PST 2014


On Friday, 7 November 2014 at 21:05:52 UTC, Freddy wrote:
> Why is size_t an alias and not a typedef(or a struct that is not
> implictly convertable)
>
> ----test.d
> void main(){
>      ulong a;
>      size_t b=a;//only compiles on 64-bit
> }
> ----
> $ dmd -m64 test
>
> $ dmd -m32 test
> test.d(3): Error: cannot implicitly convert expression (a) of
> type ulong to uint

size_t is meant to have a range large enough to hold any offset 
to any pointer on your platform.  On 32 bit this is a 32 bit 
unsigned integer (uint) and on 64 bit it is a 64 bit unsigned 
integer (ulong).  So on 32 bit size_t is the same as uint and on 
64 bit it is the same as ulong.  So it makes sense that this 
doesn't compile on 64 bit systems.

I could see you making an argument that a ulong should never be 
implicitly converted to a size_t because that could produce 
different results depending on the platform, but I don't think 
that if size_t is 32 bits that ulong should ever be implicitly 
converted to a size_t.  If you want to do something like that you 
better know what your doing and requiring an explicit cast is a 
reasonable way to protect against unsafe casts.


More information about the Digitalmars-d mailing list