Apparently unsigned types really are necessary

Marco Leise Marco.Leise at gmx.de
Sun Jan 22 09:44:49 PST 2012


Am 22.01.2012, 18:00 Uhr, schrieb Ali Çehreli <acehreli at yahoo.com>:

> On 01/22/2012 04:49 AM, Jonathan M Davis wrote:
>
>  > Another potentially nasty situation is subtraction. It
>  > can do fun things when you subtract one unsigned type from another if  
> you're
>  > not careful (since if the result is negative and is then assigned to  
> an
>  > unsigned integer...).
>
> No need to assign the result explicitly either. Additionally, the  
> subtraction is someties implicit.
>
> When the expression has an unsigned in it, the temporary result is  
> unsigned by the language rules since C:
>
> import std.stdio;
>
> int foo()
> {
>      return -2;
> }
>
> uint bar()
> {
>      return 1;
> }
>
> void main()
> {
>      writeln(foo() + bar());
> }
>
> The program above prints 4294967295.
>
> It may make perfect sense for bar() to return an unsigned type (like  
> arrays' .length property), but every time I decide on an unsigned type,  
> I think about the potentially-unintended implicit conversion to unsigned  
> that may bite the users of bar().
>
> Ali

That's a valid point, if the order "foo() + bar()" makes sense and a  
negative value is expected. After all foo() and bar() must be related  
somehow, otherwise you wouldn't add them. In this case, if the expected  
result is a signed int, I would make bar() return a signed int as well and  
not treat that case like array.length!


More information about the Digitalmars-d mailing list