Apparently unsigned types really are necessary

Ali Çehreli acehreli at yahoo.com
Sun Jan 22 09:00:54 PST 2012


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



More information about the Digitalmars-d mailing list