May 25, 2013 Re: Problem with object understanding and datatypes | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Namal | On 05/25/2013 11:57 AM, Namal wrote:
> I have one more question towards using unsigned datatype
>
> assert(sint(-2_147_483_647) - sint(3) == sint(-2_147_483_648));
> assert(sint(-2_147_483_647) - sint(3) == sint(2_147_483_648));
>
> Here I get an error for the second line, because it cannot be convertet
It helps a lot if you tell the error message. After making some assumption I was able to produce an error message:
Error: cannot implicitly convert expression (2147483648L) of type long to int
It makes sense if sint is Saturated!int. 2147483648 is long but the struct member is int.
> if i use unsigned
>
> assert(sint(-2_147_483_647) - sint(3) == sint(-2_147_483_648));
> assert(sint(-2_147_483_647) - sint(3) == sint(2_147_483_648u));
>
> it makes no difference and I get an error.
This time 2_147_483_648u is a uint which happens to have automatic conversion to int. Automatic type conversions can be extremely confusing. Let's see...
import std.stdio;
struct S
{
int i;
}
void main()
{
// uint converts to int:
auto s = S(1u);
int i;
uint u = uint.max;
// same:
i = u;
// Surprising result:
assert(i == -1);
}
These rules are both because they are same or similar in C and also for convenience. But yes, they can be confusing...
Ali
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply