www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - signed -> unsigned

reply Fawzi Mohamed <fmohamed mac.com> writes:
This topic came up several times already, but I recently thought about 
it again, and I think that there is an improvement that could be done.

There are people that dislike the idea of signed-> unsigned conversion, 
I am not one of those.
I think that it is very useful.
For example 2u-1 will give the expected answer using the conversion to 
unsigned, and I would argue that also 1u-2 has an answer that is 
perfectly logical, and I doubt it will introduce bugs that a signed 
type or casting would avoid.

Still there is a problem if a type that from signed has been converted 
to unsigned, will then be implicitly converted to another type.
Single signed->unsigned implicit casts are fine, but *subsequent* 
implicit casts are probably wrong.
For example 1UL+(1u-1) gives a result that is (I would argue) 
unexpected by most.

A way to avoid this is to consider all implicit casts (and if one want 
to be more stringent also results of subtractions of unsigned types) as 
the final type, and not implicitly castable to any other type.
I am not sure how hard that would be to implement in dmd, but from the 
usage it would still be very inline with D philosophy: C code would 
probably still work, and if not it will clearly fail, not give 
different results.

Such a solution would (I think) basically fix most bugs related to 
signed-unsigned handling, and still be convenient to use, and 
reasonably easy to explain: signed -> unsigned conversion is implicit, 
but fixes the bit representation (because it is clear that to do such a 
conversion one has either to know that the value is positive or to 
commit itself to a given bit size), so any further implicit conversion 
are not allowed (the same could be done for subtractions of unsigned 
values, as also those might "fix" the bit size).

Fawzi
Apr 12 2010
parent Fawzi Mohamed <fmohamed mac.com> writes:
On 2010-04-12 15:19:28 +0200, Fawzi Mohamed <fmohamed mac.com> said:

 1UL+(1u-1)
ehm my example should (obviously?) have been 1UL+(1u-2) sorry about the mistake
Apr 12 2010