Is there any reason why arithmetic operation on shorts and bytes return int?
js.mdnq
js_adddot+mdng at gmail.com
Tue Dec 11 15:09:05 PST 2012
On Tuesday, 11 December 2012 at 14:02:52 UTC, d coder wrote:
> On Tue, Dec 11, 2012 at 7:05 PM, Peter Alexander <
> peter.alexander.au at gmail.com> wrote:
>
>> That's the whole point. What you are doing is dangerous, so it
>> requires
>> the cast.
>>
>
>
> What I am doing is not dangerous. I am operating at byte/short
> level.
> Tell me, if what I am doing is dangerous, how come doing the
> following is
> not dangerous. It is allowed by D.
>
> int a, b, c;
> a = b + c;
>
> Also the sense of safety that you get for short and byte too is
> not
> complete. Consider:
>
> void main() {
> import std.stdio;
> ushort a = ushort.max;
> ushort b = ushort.max;
> a += b;
> writeln(a);
> }
>
>
> Is it too much to ask for consistent behavior across the
> built-in types?
>
> Regards
> - Puneet
What if you create a new type that creates the proper
functionality and does the implicit casting and such? This would
hide away the details but maybe at a cost of efficiency.
e.g.,
struct bbyte {
byte value;
...
}
bbyte a; bbyte b;
b = a + b; // uses bbyte's operators and casts to do the
computation and assignment but then returns a bbyte instead of an
int.
You should have no problems implicitly converting bbyte to built
in types or built in types to bbyte.
More information about the Digitalmars-d
mailing list