Is there any reason why arithmetic operation on shorts and bytes return int?

monarch_dodra monarchdodra at gmail.com
Tue Dec 11 04:56:37 PST 2012


On Tuesday, 11 December 2012 at 12:30:35 UTC, d coder wrote:
> For some more clarity, when I compile the following code:
>
> void main() {
>   import std.stdio;
>   byte a;
>   byte b;
>   byte c = a + b;
> }
>
> I get error:
> test.d(6): Error: cannot implicitly convert expression 
> (cast(int)a +
> cast(int)b) of type int to byte
>
> Why is D trying to convert bytes and shorts to integers before 
> applying any
> arithmetic operator?
>
> Regards
> - Puneet

As I answered in the other thread, it's just the way things are 
done, since the days of C.

What D brings to the table though is extra safety:

void main() {
    import std.stdio;
    ubyte a = 200;
    ubyte b = 200;
    ubyte c = a + b;
}

here, a + b will have a value of 400, and have overflown its 
ubyte storage. If you want to store the result back into a ubyte, 
then you'll have to do it explicitly. In this way, if overflow 
*does* occur, you can't blame the compiler for doing it behind 
your back...


More information about the Digitalmars-d mailing list