size_t index=-1;

tsbockman via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Mar 21 13:27:42 PDT 2016


On Monday, 21 March 2016 at 17:38:35 UTC, Steven Schveighoffer 
wrote:
> Your definition of when "implicit casting is really a bad idea" 
> is almost certainly going to include cases where it really 
> isn't a bad idea.

This logic can be applied to pretty much any warning condition or 
safety/correctness-related compiler feature; if it were followed 
consistently the compiler would just always trust the programmer, 
like an ancient C or C++ compiler with warnings turned off.

> The compiler isn't all-knowing, and there will always be cases 
> where the user knows best (and did the conversion 
> intentionally).

That's what explicit casts are for.

> An obvious one is:
>
> void foo(ubyte[] x)
> {
>   int len = x.length;
> }
>
> (let's assume 32-bit CPU) I'm assuming the compiler would 
> complain about this, since technically, len could be negative! 
> Disallowing such code or requiring a cast is probably too much.

But that *is* a bad idea - there have been real-world bugs caused 
by doing stuff like that without checking.

With respect to your specific example:

1) The memory limit on a true 32-bit system is 4GiB, not 2GiB. 
Even with an OS that reserves some of the address space, as much 
as 3GiB or 3.5GiB may be exposed to a user-space process in 
practice.

2) Many 32-bit CPUs have Physical Address Extension, which allows 
them to support way more than 4GiB. Even a non-PAE-aware process 
will probably still be offered at least 3GiB on such a system.

3) Just because your program is 32-bit, does *not* mean that it 
will only ever run on 32-bit CPUs. On a 64-bit system, a single 
32-bit process could easily have access to ~3GiB of memory.

4) Even on an embedded system (which D doesn't really support 
right now, anyway) with a true, 2GiB memory limit, you still have 
the problem that such highly platform-dependent code is difficult 
to find and update when the time comes to port the code to more 
powerful hardware.

These kinds of things are why D has fixed-size integer types: to 
encourage writing portable code, without too many invisible 
assumptions about the precise details of the execution 
environment.


More information about the Digitalmars-d-learn mailing list