automatic int to short conversion - the HELL?

bearophile bearophileHUGS at lycos.com
Fri Sep 19 17:23:17 PDT 2008


Sean Kelly:
> In C, the above code implicitly converts int(0) to short and int(1) to 
> unsigned.  If literals had a type and implicit conversions were illegal, 
> this code would have to be:
>      short i = (short)0;
>      unsigned j = (unsigned)1;
> which obviously stinks.  However, typed literals plus allowed conversion 
> also makes this legal:
> 
>      unsigned k = -2;
> 
> which makes no sense, given the types involved.

Let's see, this is a quick rough list of things that can be done:
- Type conversions can be implicit only when upcasting. All downcasting require an explicit cast.
- Literals are controlled at compile time. So at compile time the compiler can perform an implicit cast safely, even downcasting.
- < > between signed and unsigned numbers requires automatic upcasting (uint > int becomes long > long), or manual casting.
- Things like unsigned k = -2; are of course disallowed.
- In arrays and other collections the length can be named "size" and it has to be a signed integer as long as the CPU word.
- When not in -release mode the executable contains overflow controls on all integral operations (Delphi almost does this, with a trick). They can be removed in release mode.
- cent/ucent can be introduced and maybe it can be silently used by the compiler to avoid some bugs, when not in release mode.
- Eventually, later a multiprecision integer type, optimized for 4-10 bytes long integers can be used here and there, but the compiler can replace its operations with signed or unsigned operations among CPU-word integrals everywhere there's no risk of overflow.
- Octal literals have to be improved.

Similar things can help remove some of the bugs from the future D2 programs.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list